如何使用rsync在Python中以递归方式计算目录中可用文件的数量?

问题描述:

我想在Python中使用rsync在远程服务器路径中递归计算文件数量?我试过这样做:如何使用rsync在Python中以递归方式计算目录中可用文件的数量?

def find_remote_files(source, password): 
    cmdline = ['sshpass', '-p', password, 'rsync', '--recursive', source] 
    with open(os.devnull, "w") as devnull: 
     proc = subprocess.Popen(cmdline, stdout=subprocess.PIPE, stderr=devnull) 
     try: 
      for entry in proc.stdout: 
       items = entry.strip().split(None, 4) 
       if not items[0].startswith("d"): 
        yield lent(items[4]) 
      proc.wait() 
     except: 
      # On any exception, terminate process and re-raise exception. 
      proc.terminate() 
      proc.wait() 
      raise 

它适用于我有少量文件的情况。但如果我有超过3000个文件,rsync将需要很长时间才能将其存储在列表中,并再次计算长度。这就是为什么,我想知道是否有一个rsync命令来计算文件。

我会使用不同的方法使用fabric,这是一个执行远程命令的好工具。

from fabric.api import run, env 
env.host_string = 'example.org' 
output = run('find /tmp -type f | wc -l') 
num_files = int(output) 

现在,您的变量的文件数为num_files。我刚刚使用find命令从目录/tmp开始递归搜索文件,并用wc -l对返回的行进行计数。

+0

我应该在哪里放置host_string ='example.org'的用户名和密码? – user2545177

+0

只需查看fabric上的文档:http://docs.fabfile.org/en/1.6/ - 您可以在命令行或“fabfile”中提供主机和用户。不应该使用密码,因为通常的方法是使用不带密码的ssh密钥。 – mawimawi