2015-03-03 153 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

相關問題