Paramiko/scp - 检查远程主机上是否存在文件 [英] Paramiko / scp - check if file exists on remote host
问题描述
我正在使用 Python Paramiko 和 scp 在远程机器上执行一些操作.我工作的某些机器要求文件在其系统上本地可用.在这种情况下,我使用 Paramiko 和 scp 来复制文件.例如:
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()
我的问题是,在尝试 scp 之前,如何检查远程计算机上是否存在localfile"?
My question is, how can I check to see if 'localfile' exists on the remote machine before I try the scp?
我想在可能的情况下尝试使用 Python 命令,即不要使用 bash
I'd like to try and use Python commands where possible i.e. not bash
推荐答案
改用 paramiko 的 SFTP 客户端.此示例程序在复制之前检查是否存在.
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")
这篇关于Paramiko/scp - 检查远程主机上是否存在文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!