使用 Paramiko 执行远程主机的命令并下载命令完成后创建的文件

Execute command of remote host with Paramiko and download a file that the command creates once it completes

我的代码使用 Paramiko 登录远程 Unix 主机

  1. grep 远程 Linux 主机上的字符串,然后将结果写入新文件 /tmp/file.<timestamp>.txt。 – 这很好
  2. 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 by doing so. For a correct solution, see Paramiko "Unknown Server".

的保护