1

好吧,我在远程站点 authorized_keys 文件上有一个受限命令关联,如下所示:

command="python /usr/share/my_script.py" ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDxiK......

这个脚本应该带参数。

在本地站点上,我尝试使用 paramiko 使用本地参数启动远程脚本:

import sys, paramiko

host = '192.168.1.10'
port = 22
restricted_key = '/root/.ssh/restricted_key'

client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect(host, port=port, username=user, key_filename=restricted_key)

arg1, arg2, arg3 = ('python', 'is', 'cool')
command = 'python /usr/share/my_script.py %s %s %s' % (arg1, arg2, arg3)
stdin, stdout, stderr = client.exec_command(command)

if not stderr.readlines():
    return stdout.readlines()
else:
    raise IOError

这是远程脚本 python /usr/share/my_script.py:

if __name__ == "__main__":
try:
    arg1, arg2, arg3 = (sys.argv[1], sys.argv[2], sys.argv[3])
    open('/tmp/just_a_test', 'a+').write('%s %s %s' % (arg1, arg2, arg3))
except Exception, e:
    print 'ERROR : %s' % str(e)

脚本退出时没有错误,但似乎没有启动远程执行。我希望能够以 100% python 的方式做到这一点,因为这是可能的。

4

1 回答 1

1

在 authorized_keys 命令中添加环境变量 $SSH_ORIGINAL_COMMAND 就可以了。

command="python /usr/share/my_script.py $SSH_ORIGINAL_COMMAND" ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQDDxiK......

然后在我的 paramiko 执行中,我只是将要发送的参数发送到远程命令,如下所示:

command = '%s %s %s' % (arg1, arg2, arg3)
stdin, stdout, stderr = client.exec_command(command)
于 2013-02-20T22:40:14.167 回答