【问题标题】:Execute command of remote host with Paramiko and download a file that the command creates once it completes使用 Paramiko 执行远程主机的命令,并下载命令完成后创建的文件
【发布时间】:2021-03-27 23:16:31
【问题描述】:

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

  1. grep 远程 Linux 主机上的字符串,然后将结果写入新文件 /tmp/file.<timestamp>.txt。 – 这很好用
  2. sftp 到远程 Linux 主机并获取我刚刚从我的grep 创建的文件。 – 这是我遇到问题的步骤。

远程系统 = Linux 本地系统 = Windows

问题是当我从我的 Unix 主机 sftp 获取文件时,一旦它到达我的 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()

【问题讨论】:

    标签: python sftp paramiko


    【解决方案1】:

    您没有等待命令完成。所以你正在下载一个不完整的文件。

    要等待命令完成,您可以执行以下操作:

    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"

    【讨论】:

    • 嗨,马丁,非常感谢。这正是我需要的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    • 2021-05-07
    相关资源
    最近更新 更多