简体   繁体   English

Python-如何对通过ssh访问的目录中的文件运行for循环?

[英]Python - How to run a for loop over files in a directory accessed via ssh?

I'm trying to write a function where it would ssh into a remote host and for every file in a directory, process it. 我正在尝试编写一个函数,将它SSH到远程主机中,并对目录中的每个文件进行处理。

For example, my current function for the for loop is: 例如,我当前的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...

How do I wrap the above function in a ssh connection, something in the line of this: 我如何将以上函数包装在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()

It would probably be easier to copy your Python script (the one with the loop) onto your remote machine using SCP and then running the copied Python script on the remote machine. 使用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')

Then on your local, you may do: 然后,您可以在本地执行以下操作:

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

This has a hardcoded path to /tmp though. 但是,这具有到/tmp的硬编码路径。 You could make your file accept command line arguments in order to handle any path you pass at run time. 您可以使文件接受命令行参数,以便处理在运行时传递的任何路径。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM