我使用pysftp和Python3.7来设置SFTP客户端脚本。
我的代码(简化和最小化):
import pysftp
import sys
# Variables
destination_dir = 'BOGUS_DIR'
server = 'myserver.mydomain.com'
user = 'my_user'
key = 'my_key'
port = 22
# cnopts
mycnopts = pysftp.CnOpts()
mycnopts.log = True
mycnopts.compression = True
mycnopts.ciphers = None
mycnopts.hostkeys = None
try:
with pysftp.Connection(server, username=user, private_key=key, port=port, cnopts=mycnopts) as sftp:
try:
with sftp.cd(destination_dir):
print("OK cd worked")
except:
print("NOT OK cd failed")
e = sys.exc_info()
print("Exception: {0}".format(e))
if sftp.isdir(destination_dir):
print("OK isdir")
else:
print("NOT OK isdir")
except:
print("Connection failure.")
e = sys.exc_info()
print("Exception: {0}".format(e))输出是:OK cd工作的
但我知道的一个事实是,BOGUS_DIR确实存在而不是。这就像pysftp不会在cd()上引发异常,或者我抓错了它(因此我的python代码没有正确完成)。
对于isdir(),无论我作为参数放置什么,它总是返回True,即使目录不存在。
如果将连接参数更改为错误,则会捕获连接失败异常。
pyftp处理异常是错误的,还是我的代码在这里出错了?我不应该信任pysftp直接使用Paramiko吗?
发布于 2020-04-15 17:14:20
好吧,我想我想出来了。
如果目录不存在,sftp.cd()不会引发异常。只有坏目录上的操作才行。所以如果我像这样修改我的代码:
....
try:
with sftp.cd(destination_dir):
sftp.listdir()
print("OK ce worked")
except:
print("NOT OK cd failed")
e = sys.exc_info()
print("Exception: {0}".format(e))
....这样我就得到了一个异常,因为sftp.listdir()不能处理一个不存在的目录。
几乎像sftp.cd一样,除了设置当前目录的值之外,什么也不做,而实际上没有对它做任何操作。
发布于 2020-04-15 15:31:58
如果目录不存在,则从试图运行命令的远程shell中获得一个错误。在这段代码中,您试图捕获只能由sftp引发的异常。也许,您应该在执行每个shell命令后检查sftp模块应该返回的状态代码。
https://stackoverflow.com/questions/61232360
复制相似问题