Paramiko / scp - check if a file exists on a remote host

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

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 if a local file exists on the remote computer before I try scp?

I would like to try and use Python commands where possible, i.e. not bash

+4
source share
2 answers

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")
+10

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
0

All Articles