2017-02-14 54 views
0

我想写一个函数,它会ssh到远程主机和目录中的每个文件,处理它。Python - 如何运行for循环通过ssh访问的目录中的文件?

例如,我对对回路电流的功能是:

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硬编码的路径,但。你可以让你的文件接受命令行参数,以便处理你在运行时传递的任何路径。