2017-02-14 4 views
0

私は、リモートホストにsshとなるディレクトリにあるすべてのファイルに対して、関数を記述しようとしています。Python - ssh経由でアクセスされるディレクトリ内のファイルに対してforループを実行するには?

例えば、forループのための私の現在の機能は次のとおりです。

import fnmatch, os  
def process_logfiles_in_remote_directory(remotedir): 
    for filename in os.listdir(remotedir): 
     if fnmatch.fnmatch(filename, '*.log'): 
      filename = os.path.join(remotedir, filename) 
      ## Do something here... 

私は、この行で、ssh接続で何かを上記の関数をラップするにはどうすればよい:

ssh_client = paramiko.SSHClient() 
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh_client.connect("www.remotehost.com", username="admin", password="testing") 
stdin, stdout, stderr = ssh_client.exec_command(process_logfiles_in_remote_directory('/tmp')) 
ssh_client.close() 
+0

[pythonでsftpを接続した後にディレクトリ内のすべてのフォルダとファイルを一覧表示する方法](http://stackoverflow.com/questions/12295551/how-to-list-all-the-folders-接続後のディレクトリおよびファイル) – kawadhiya21

答えて

0

それをSCPを使用してリモートマシンにPythonスクリプト(ループを持つスクリプト)をコピーしてから、リモートマシンでコピーしたPythonスクリプトを実行する方が簡単でしょう。

import fnmatch, os  
def process_logfiles_in_remote_directory(remotedir): 
    for filename in os.listdir(remotedir): 
    if fnmatch.fnmatch(filename, '*.log'): 
     filename = os.path.join(remotedir, filename) 
     ## Do something here... 
if __name__ == '__main__': 
    process_logfiles_in_remote_directory('/tmp') 

次に、ローカルに、あなたが行うことがあります。

ssh_client = paramiko.SSHClient() 
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 
ssh_client.connect("www.remotehost.com", username="admin", password="testing") 
stdin, stdout, stderr = ssh_client.exec_command("python <filename>.py") 
ssh_client.close() 

これはしかし/tmpにハードコードされたパスを持っています。実行時に渡すパスを処理するために、ファイルがコマンドライン引数を受け入れるようにすることができます。

関連する問題