Search code examples
pythonpython-2.7sshscpparamiko

Paramiko / scp - check if file exists on remote host


I'm using Python Paramiko and scp to perform some operations on remote machines. Some machines I work on require files to be available locally on their system. When this is the case, I'm using Paramiko and scp to copy the files across. For example:

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()

My question is, how can I check to see if 'localfile' exists on the remote machine before I try the scp?

I'd like to try and use Python commands where possible i.e. not bash


Solution

  • Use paramiko's SFTP client instead. This example program checks for existence before copy.

    #!/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")