2016-07-26 211 views
0

我有一個python程序需要通過ssh在遠程系統上調用腳本。使用參數通過ssh使用python腳本的命令運行腳本

這個ssh調用需要在指定的日期發生(一次),可以通過linux命令完成。

我可以使用我的python程序中的os模塊或subprocess模塊來調用這兩個外部bash命令。將某些參數傳遞給遠程腳本時會出現問題。

除了遠程運行並在稍後的日期,我希望調用的(bash)腳本需要傳遞給它的幾個參數,這些參數是我希望傳遞給腳本的python變量。

user="[email protected]" 
arg1="argument with spaces" 
arg2="two" 
cmd="ssh "+user+"' /home/user/path/script.sh "+arg1+" "+arg2+"'" 
os.system(cmd) 

的爭論之一是它包含空格,但在理想情況下被作爲一個參數傳遞的字符串;

例如:

./script.sh "Argument with Spaces" 其中$ 1等於"Argument with Spaces"

我試圖逃避在Python和字符串本身和周圍的整個使用重音符的雙和單引號的各種組合ssh命令。最成功的版本根據需要使用參數調用腳本,但忽略at命令並立即運行。

Python中是否有一個乾淨的方式來完成這個?

回答

2

新的答案

現在你編輯你的問題,你或許應該使用的格式字符串

cmd = '''ssh {user} "{cmd} '{arg0}' '{arg1}'"'''.format(user="[email protected]",cmd="somescript",arg0="hello",arg2="hello world") 
print cmd 

老答案

我想你可以使用一個-cssh開關執行一些代碼遠程計算機(ssh [email protected] -c "python myscript.py arg1 arg2"

或者我需要比,所以我用這個的paramiko包裝類以上(你需要安裝的paramiko)

from contextlib import contextmanager 
import os 
import re 
import paramiko 
import time 


class SshClient: 
    """A wrapper of paramiko.SSHClient""" 
    TIMEOUT = 10 

    def __init__(self, connection_string,**kwargs): 
     self.key = kwargs.pop("key",None) 
     self.client = kwargs.pop("client",None) 
     self.connection_string = connection_string 
     try: 
      self.username,self.password,self.host = re.search("(\w+):(\w+)@(.*)",connection_string).groups() 
     except (TypeError,ValueError): 
      raise Exception("Invalid connection sting should be 'user:[email protected]'") 
     try: 
      self.host,self.port = self.host.split(":",1) 
     except (TypeError,ValueError): 
      self.port = "22" 
     self.connect(self.host,int(self.port),self.username,self.password,self.key) 
    def reconnect(self): 
     self.connect(self.host,int(self.port),self.username,self.password,self.key) 

    def connect(self, host, port, username, password, key=None): 
     self.client = paramiko.SSHClient() 
     self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
     self.client.connect(host, port, username=username, password=password, pkey=key, timeout=self.TIMEOUT) 

    def close(self): 
     if self.client is not None: 
      self.client.close() 
      self.client = None 

    def execute(self, command, sudo=False,**kwargs): 
     should_close=False 
     if not self.is_connected(): 
      self.reconnect() 
      should_close = True 
     feed_password = False 
     if sudo and self.username != "root": 
      command = "sudo -S -p '' %s" % command 
      feed_password = self.password is not None and len(self.password) > 0 
     stdin, stdout, stderr = self.client.exec_command(command,**kwargs) 
     if feed_password: 
      stdin.write(self.password + "\n") 
      stdin.flush() 

     result = {'out': stdout.readlines(), 
       'err': stderr.readlines(), 
       'retval': stdout.channel.recv_exit_status()} 
     if should_close: 
      self.close() 
     return result 

    @contextmanager 
    def _get_sftp(self): 
     yield paramiko.SFTPClient.from_transport(self.client.get_transport()) 

    def put_in_dir(self, src, dst): 
     if not isinstance(src,(list,tuple)): 
      src = [src] 
     print self.execute('''python -c "import os;os.makedirs('%s')"'''%dst) 
     with self._get_sftp() as sftp: 
      for s in src: 
       sftp.put(s, dst+os.path.basename(s)) 

    def get(self, src, dst): 
     with self._get_sftp() as sftp: 
      sftp.get(src, dst) 
    def rm(self,*remote_paths): 
     for p in remote_paths: 
      self.execute("rm -rf {0}".format(p),sudo=True) 
    def mkdir(self,dirname): 
     print self.execute("mkdir {0}".format(dirname)) 
    def remote_open(self,remote_file_path,open_mode): 
     with self._get_sftp() as sftp: 
      return sftp.open(remote_file_path,open_mode) 

    def is_connected(self): 
     transport = self.client.get_transport() if self.client else None 
     return transport and transport.is_active() 

那麼你可以使用它,如下所示

client = SshClient("username:[email protected]") 
result = client.execute("python something.py cmd1 cmd2") 
print result 

result2 = client.execute("cp some_file /etc/some_file",sudo=True) 
print result2 
相關問題