在使用paramiko
库进行SFTP操作时,如果遇到AttributeError: 'SFTPClient' object has no attribute 'exists'
错误,这意味着你尝试调用的.exists()
方法并不直接存在于paramiko.SFTPClient
对象中。
虽然SFTPClient
类没有内置的.exists()
方法,但你可以通过尝试执行.stat()
方法并捕获(paramiko.ssh_exception.SFTPFileNotFoundError)
异常来判断文件或目录是否存在:
import paramiko
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('hostname', username='username', password='password')
sftp = ssh.open_sftp()
try:
sftp.stat('/path/to/file_or_directory')
print("The file or directory exists.")
except paramiko.ssh_exception.SFTPFileNotFoundError:
print("The file or directory does not exist.")
ssh.close()
这段代码尝试获取指定路径的文件状态信息,如果没有找到该文件或目录,则会抛出SFTPFileNotFoundError
异常,从而可以推断该路径不存在于远程服务器上。