通过子进程在远程计算机上执行python脚本时出错

时间:2015-03-03 01:40:02

标签: python ssh subprocess

我试图通过subprocess执行python脚本。首先,我尝试通过以下代码执行本地计算机上存在的python脚本:

str = 'abc'
sub_result = subprocess.Popen([sys.executable,"./script.py"] + str)

这工作正常。现在我试图通过subprocess执行远程机器上的脚本。首先,我无法通过subprocess.Popen()找到任何关于如何通过本地机器执行此操作的示例。然后我尝试在以下代码中使用subprocess.call(),但我遇到了问题:

str = 'abc'
sub_result = subprocess.call('ssh username@hostname python ./script.py' + str)

我收到以下错误:

File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 524, in call
    return Popen(*popenargs, **kwargs).wait()
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/subprocess.py", line 1308, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory

我正在做的错误是什么,以及如何在password命令中提及连接的ssh

更新:根据@ musiphil的回答,我修改了我的代码而我没有使用:

str = 'abc'
sub_result = subprocess.call(['ssh', 'username@hostname', 'python', './script.py'] + str)

但是我收到了这个错误:

    ssh_askpass: exec(/usr/libexec/ssh-askpass): No such file or directory
Permission denied, please try again.
ssh_askpass: exec(/usr/libexec/ssh-askpass): No such file or directory
Permission denied (publickey,gssapi-keyex,gssapi-with-mic,password).

2 个答案:

答案 0 :(得分:3)

除非您还指定shell=True

,否则您应该提供argv样式列表
str = 'abc'
sub_result = subprocess.call(
    ['ssh', 'username@hostname', 'python', './script.py', str])

请参阅https://docs.python.org/2/library/subprocess.html#subprocess.call

答案 1 :(得分:1)

您可以借助sshpass命令在ssh上提及密码。

    ['sshpass', '-p', 'password', 'ssh','username@%s' % address]