限定SSH登录的命令执行

最近需要创建一个用于监控主机性能的帐号,由于是核心的生产服务器,这个帐号登录需要严格限定执行常见的sysstat, top等性能命令,完成后就要退出登录。查了一些资料后了解authorized_keys中的command等一系列选项可以用于限定使用公钥验证登录后只能执行的命令,服务器在完成该脚本额执行后,SSH也会中端和客户端的通信。
authorized_keys中的command选项描述如下:
command=”command”
Specifies that the command is executed whenever this key is used
for authentication. The command supplied by the user (if any) is
ignored. The command is run on a pty if the client requests a
pty; otherwise it is run without a tty. If an 8-bit clean chan-
nel is required, one must not request a pty or should specify
no-pty. A quote may be included in the command by quoting it
with a backslash. This option might be useful to restrict cer-
tain public keys to perform just a specific operation. An exam-
ple might be a key that permits remote backups but nothing else.
Note that the client may specify TCP and/or X11 forwarding unless
they are explicitly prohibited. The command originally supplied
by the client is available in the SSH_ORIGINAL_COMMAND environ-
ment variable. Note that this option applies to shell, command
or subsystem execution.

$SSH_ORIGINAL_COMMAND 客户端连接提供的命令可以使用这个环境变量来获得
首先在Linux Client的Shell下可以使用ssh-keygen创建一对key。

拷贝这个pub key到server上

此时,我们在$HOME/.ssh/authorized_keys可以找到对应的公钥文本:
ssh-rsa …
在这个公钥文本之前加入command命令:
command=”/root/showperf.sh $SSH_ORIGINAL_COMMAND” ssh-rsa …
限定client登录执行的命令可以写在showperf.sh这个脚本中,使用case语句来实现,下面是一个简单的实现

登录测试如下:

^^
参考:

http://man.he.net/man5/authorized_keys

http://cybermashup.com/2013/05/14/restrict-ssh-logins-to-a-single-command/

Posted in Linux, Ops.