2015-03-03 151 views
2

我试图通过subprocess执行python脚本。首先,我尝试通过以下代码执行本地机器上存在的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 [email protected] 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 

什么是我做了错误,还我怎么能提ssh命令中的password连接?

UPDATE:基于@ musiphil的回答我修改了代码,并没有我使用:

str = 'abc' 
sub_result = subprocess.call(['ssh', '[email protected]', '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). 
+1

在运行SSH问题之前,您正在运行的代码应引发TypeError(只能列出并列列表(不是“str”))。 – 2015-03-03 03:45:36

+0

@jd。我已经把'str'列为清单。我忘了更新以上代码 – user2966197 2015-03-03 03:46:59

+0

@jd中的str。我修改了上面更新部分中的代码 – user2966197 2015-03-03 03:50:52

回答

3

你应该给一个argv的风格列表中,除非您还指定shell=True

str = 'abc' 
sub_result = subprocess.call(
    ['ssh', '[email protected]', 'python', './script.py', str]) 

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

+0

以及如何使用ssh提及密码? – user2966197 2015-03-03 01:47:30

+0

当我尝试执行上面的代码时,出现以下错误:'ssh_askpass:exec(/ usr/libexec/ssh-askpass):没有这样的文件或目录 主机密钥验证失败.' – user2966197 2015-03-03 01:58:08

+0

您可以通过以下方式连接到远程主机:手动运行SSH?在任何情况下,子流程方法都会让工作变得单调乏味。你可以尝试在Python中实现SSH协议的'paramiko'。 – 2015-03-03 03:41:34

相关问题