【问题标题】:Paramiko / scp - check if file exists on remote hostParamiko / scp - 检查远程主机上是否存在文件
【发布时间】:2016-07-29 01:42:49
【问题描述】:

我正在使用 Python Paramiko 和 scp 在远程机器上执行一些操作。我工作的一些机器要求文件在他们的系统上本地可用。在这种情况下,我使用 Paramiko 和 scp 来复制文件。例如:

from paramiko import SSHClient
from scp import SCPClient

ssh = SSHClient()
ssh.load_system_host_keys()
ssh.connect('192.168.100.1')

scp = SCPClient(ssh.get_transport())
scp.put('localfile', 'remote file')
scp.close()

ssh.close()

我的问题是,在我尝试 scp 之前,如何检查远程计算机上是否存在“localfile”?

我想尽可能尝试使用 Python 命令,而不是 bash

【问题讨论】:

    标签: python python-2.7 ssh scp paramiko


    【解决方案1】:

    改用 paramiko 的 SFTP 客户端。此示例程序在复制之前检查是否存在。

    #!/usr/bin/env python
    
    import paramiko
    import getpass
    
    # make a local test file
    open('deleteme.txt', 'w').write('you really should delete this]n')
    
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        ssh.connect('localhost', username=getpass.getuser(),
            password=getpass.getpass('password: '))
        sftp = ssh.open_sftp()
        sftp.chdir("/tmp/")
        try:
            print(sftp.stat('/tmp/deleteme.txt'))
            print('file exists')
        except IOError:
            print('copying file')
            sftp.put('deleteme.txt', '/tmp/deleteme.txt')
        ssh.close()
    except paramiko.SSHException:
        print("Connection Error")
    

    【讨论】:

    • 感谢您的建议。 sftp 是否需要在远程机器上运行任何东西,例如 FTP?
    • 不,它应该是服务器 ssh 守护进程的一部分。我的 SFTP 无需额外配置即可工作。
    【解决方案2】:

    应该可以只使用 paramiko 结合 'test' 命令来检查文件是否存在。这不需要 SFTP 支持:

    from paramiko import SSHClient
    
    ip = '127.0.0.1'
    file_to_check = '/tmp/some_file.txt'
    
    ssh = SSHClient()
    ssh.load_system_host_keys()
    ssh.connect(ip)
    
    stdin, stdout, stderr = ssh.exec_command('test -e {0} && echo exists'.format(file_to_check))
    errs = stderr.read()
    if errs:
        raise Exception('Failed to check existence of {0}: {1}'.format(file_to_check, errs))
    
    file_exits = stdout.read().strip() == 'exists'
    
    print file_exits
    

    【讨论】:

      猜你喜欢
      • 2010-10-25
      • 2011-07-24
      • 2012-10-02
      • 1970-01-01
      • 2020-06-15
      • 2023-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多