首页 > 解决方案 > python 2.7发送的远程ssh命令

问题描述

试图弄清楚如何发送 ssh 命令。这通过 cli 工作:

ssh -i /path/myKey.pem centos@myServer.com lsb_release -a

但是当我像这样设置命令时失败:

cmd = ['ssh', '-i', '/path/myKey.pem', 'centos@myServer.com', 'lsb_release', '-a']): 
p =  Popen( cmd, shell=True, stdout=PIPE, stderr=PIPE )
        ( output, errStr ) = p.communicate()

我得到这个错误号 255:

usage: ssh [-46AaCfGgKkMNnqsTtVvXxYy] [-B bind_interface]
       #Snip other usage

有人有什么想法吗?

标签: pythonpython-2.7sshprocess

解决方案


与列表一起使用shell=True,您正在运行相当于

sh -c ssh -i /path/myKey.pem centos@myServer.com lsb_release -a

不是你想要的;它运行ssh,但它-i用作 的值$0,而不是 的第一个参数ssh。这/path/myKey.pem看起来像您要连接的主机的地址。

只是下降shell=True

p = Popen(cmd, stdout=PIPE, stderr=PIPE)

lsb_release -a虽然在这里不是问题,但 Klaus D. 建议作为单个参数传递通常是一个好主意。ssh必须将它们连接成一个字符串才能传递到sh -c远程端;不妨自己动手,以确保正确完成。

cmd = ['ssh', '-i', '/path/myKey.pem', 'centos@myServer.com', 'lsb_release -a']

推荐阅读