Paramiko/scp-检查远程主机上是否存在文件

2024-04-29 04:34:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用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


Tags: 文件fromimport机器paramikoclose远程系统
2条回答

改为使用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")

应该可以只使用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

相关问题 更多 >