如何解决使用 Paramiko 执行远程主机的命令并下载命令完成后创建的文件
我的代码使用Paramiko登录远程Unix主机
-
grep
远程 Linux 主机上的字符串,然后将结果写入新文件/tmp/file.<timestamp>.txt
。 – 这很好用 - sftp 到远程 Linux 主机并从我的
grep
获取我刚刚创建的文件。 – 这是我遇到问题的步骤。
远程系统 = Linux 本地系统 = Windows
问题是当我 sftp 从我的 Unix 主机获取文件时,一旦它到达我的 Windows 系统,该文件是空的。
我可以执行创建文件的命令并一次性执行 SFTP 吗?如果是这样,有没有关于如何将它放在本地 Windows 系统上的特定目录中的示例?或者我需要对第一个命令中的 stdout
做些什么?虽然我认为这行不通。
butler_report_dir = Path.home() / 'butler_reports'
butler_report_dir.mkdir(exist_ok=True)
req_date = req_date.strftime('%Y%m%d')
req_date = '*' + req_date + '*'
r_cat_file = '/tmp/cat_report_' + timestamp + '.txt'
ssh_client = SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(
ssh_server,username=ssh_username,password=ssh_passwd,look_for_keys=False,)
cmd_stmt = f'cd {old_arch_dir};' f'/usr/bin/gzip -cd {req_date} | grep {orderid} > {r_cat_file}'
stdin,stdout,stderr = ssh_client.exec_command(cmd_stmt)
# The Code Above seems to work fine as my file is being created with the timestamp
# This part below is where I am having the issue
file = butler_report_dir / 'cat_file.txt'
ftp_client = ssh_client.open_sftp()
stdin.close()
stdout.close()
stderr.close()
ssh_client.close()
解决方法
您不是在等待命令完成。所以你下载的是一个不完整的文件。
要等待命令完成,您可以执行以下操作:
stdin,stdout,stderr = ssh_client.exec_command(cmd_stmt)
stdout.channel.set_combine_stderr(True)
output = stdout.readlines()
ftp_client = ssh_client.open_sftp()
有关更多信息,请参阅Wait to finish command executed with Python Paramiko。
强制性警告:请勿使用 AutoAddPolicy
– 这样做您将失去对 MITM attacks 的保护。如需正确的解决方案,请参阅 Paramiko "Unknown Server"。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。