通过Python Paramiko在SSH连接时以本地参数执行受限的远程脚本
好吧,我在远程网站的 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)
这个脚本没有报错退出,但似乎没有成功执行远程操作。
我希望能完全用 Python 的方式来做到这一点,尽可能实现。
1 个回答
1
在授权的密钥命令中添加环境变量 $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)