如何通过 SSH 在另一台计算机上执行 os.walk()
操作?问题是 os.walk() 在本地计算机上执行,我想 ssh 到另一台主机,遍历目录并为其中的每个文件生成 MD5 哈希值。
到目前为止我写的内容看起来像这样(下面的代码),但它不起作用。任何帮助将不胜感激。
try:
hash_array = []
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('sunbeam', port=22, username='xxxx', password='filmlight')
spinner.start()
for root, dirs, files in os.walk(_path):
for file in files:
file_path = os.path.join(os.path.abspath(root), file)
# generate hash code for file
hash_array.append(genMD5hash(file_path))
file_nb += 1
spinner.stop()
spinner.ok('Finished.')
return hash_array
except Exception as e:
print(e)
return None
finally:
ssh.close()
最佳答案
要使用 Paramiko 以及标准文件访问接口(interface) SFTP 递归列出目录,您需要使用 SFTPClient.listdir_attr
来实现递归函数。 :
from stat import S_ISDIR, S_ISREG
def listdir_r(sftp, remotedir):
for entry in sftp.listdir_attr(remotedir):
remotepath = remotedir + "/" + entry.filename
mode = entry.st_mode
if S_ISDIR(mode):
listdir_r(sftp, remotepath)
elif S_ISREG(mode):
print(remotepath)
基于 Python pysftp get_r from Linux works fine on Linux but not on Windows 。
<小时/>或者,pysftp实现一个 os.walk 等效项:Connection.walktree
.
尽管您在使用 SFTP 协议(protocol)获取远程文件的 MD5 时会遇到麻烦。
虽然 Paramiko 通过其 SFTPFile.check
支持它,大多数 SFTP 服务器(尤其是最广泛使用的 SFTP/SSH 服务器 – OpenSSH)不支持。
请参阅:
How to check if Paramiko successfully uploaded a file to an SFTP server?和
How to perform checksums during a SFTP file transfer for data integrity?
因此,您很可能不得不求助于 shell md5sum
命令(如果您甚至具有 shell 访问权限)。一旦您无论如何都必须使用 shell,请考虑使用 shell 列出文件,因为这比通过 SFTP 快得多。
参见md5 all files in a directory tree .
使用SSHClient.exec_command
:
Comparing MD5 of downloaded files against files on an SFTP server in Python
强制警告:请勿使用 AutoAddPolicy
– 您将失去针对 MITM attacks 的保护通过这样做。正确的解决方案请参见 Paramiko "Unknown Server" 。
关于Python Paramiko 目录遍历 SFTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56671446/