2015-02-23 238 views
1

我想從本地機器運行我的python腳本。但名爲script.py的python腳本位於遠程服務器中,它具有一些參數和參數。 我曾嘗試:在python中使用ssh從遠程服務器運行腳本

#!/usr/bin/python 
import paramiko 

ssh = paramiko.SSHClient() 
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh.connect(hostname='x.x.x.x', port=22, username='root', password='passwd') 
stdin, stdout, stderr=ssh.exec_command('python /root/file/script.py') #It has some argument I want to use them from my local machine 
for i in stdout.readlines(): 
    print i.strip('\r\n') 
ssh.close() 

script.py有一些爭論。我應該如何改變這個腳本以便從我的本地機器使用參數script.py

+0

你熟悉'sys.argv'嗎?你可以在腳本中使用它來傳遞終端中的參數! https://docs.python.org/2/library/sys.html#sys.argv – Kasramvd 2015-02-23 07:54:08

+0

是的,我是...但在腳本中使用script.py的參數是可能的?怎麼樣? – MLSC 2015-02-23 07:59:08

+0

你可以在'ssh.exec_command'函數中傳遞它們! (但我不知道這個功能支持!),但'os.system'支持! – Kasramvd 2015-02-23 08:04:01

回答

0

它比人會認爲更靠譜,由於使用SSH不支持的參數列表:

import sys 
try: 
    from pipes import quote # python 2 
except ImportError: 
    from shlex import quote # python 3 

ssh.exec_command('python /root/file/script.py ' + 
    ' '.join([quote(i) for i in sys.argv[1:]]) 
) 

當運行python myprogram.py argument\ with" quotes\" and spaces",這應該通過'argument with quotes" and spaces'爲1參數傳遞給其他程序。雖然我不會保證paramiko總是做正確的事情。

+0

謝謝......但是,你把它放在回答部分中的最後一個''是什麼? – MLSC 2015-02-23 08:04:41

+0

它恰好是'ssh.exec_command'調用的懸掛右括號 – 2015-02-23 08:08:30

相關問題