2016-07-26 17 views
0

私は、ssh経由でリモートシステム上でスクリプトを呼び出す必要があるpythonプログラムを持っています。sshで引数を指定してスクリプトを実行するには、pythonスクリプトのatコマンドを使用してください。

このsshコールは、指定された日付にlinux atコマンドで実行できる必要があります。

osモジュールまたはsubprocessモジュールをPythonプログラムから使用して、これらの外部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) 

これらの引数の1つは、空白を含む文字列ですが、理想的には単一の引数として渡されます。例えば

:$ 1私はPythonと、文字列自体と全体の周りの墓のアクセントの使用の両方に二重および単一引用符をエスケープの様々な組み合わせを試してみました"Argument with Spaces"

に等しい

./script.sh "Argument with Spaces" sshコマンド。最も成功したバージョンは、必要に応じて引数を指定してスクリプトを呼び出しますが、atコマンドは無視してすぐに実行されます。

これを達成するために、Python内にクリーンな方法がありますか?

答えて

2

新しい答え、あなたはおそらく、書式指定文字列

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

は、私はあなたが-cを使用することができると思う古い答えを使用する必要がありますあなたの質問を編集したことを今

sshと切り替えて、コードを実行してくださいリモートマシン(ssh [email protected] -c "python myscript.py arg1 arg2"

代わりに、私はので、私は

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 
を次のようにあなたがそれを使用することができます

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() 

(あなたはparamikoをインストールする必要があります)このparamikoのラッパークラスを使用し、それ以上を必要と

関連する問題