使用Python Paramiko传输图片文件出现Failure提示的问题
问题排查与解决方案
核心问题:目标路径指定错误
你的代码中sftp_client.put的目标路径是/home,这是一个目录,SFTP协议要求上传时必须指定完整的目标文件名,而非仅目录路径。服务器无法自动推断文件保存名称,这是导致上传失败的最可能原因。
修改方式:将目标路径改为包含文件名的完整路径,示例:
sftp_client.put("screenshot.png", "/home/your_username/screenshot.png")
替换your_username为服务器上的实际用户名,确保路径指向你有写入权限的目录。
其他可能的原因及验证方法
- 权限不足:
/home目录通常仅root用户有写入权限,普通用户无法直接操作。确认目标目录是你有权限访问的路径(比如自身主目录/home/your_username/)。 - 本地文件异常:检查本地
screenshot.png是否成功生成,可添加文件校验代码:import os if not os.path.exists("screenshot.png"): print("本地截图文件不存在") else: print(f"本地文件大小:{os.path.getsize('screenshot.png')}字节") - 捕获详细错误信息:Paramiko的SFTP操作可能返回错误但未抛出显性异常,建议添加异常捕获:
try: sftp_client.put("screenshot.png", "/home/your_username/screenshot.png") print("上传成功") except Exception as e: print(f"上传失败:{str(e)}")
优化后的完整代码示例
from PIL import ImageGrab import paramiko import os class Client: def __init__(self, hostname, username, password): self.hostname = hostname self.username = username self.password = password self.client = paramiko.SSHClient() def connect(self): self.client.load_system_host_keys() self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) self.client.connect(hostname=self.hostname, username=self.username, password=self.password, port=22) def close(self): self.client.close() # 生成截图并校验 ImageGrab.grab().save("screenshot.png") if not os.path.exists("screenshot.png"): print("本地截图生成失败") exit() # 连接服务器并上传 client = Client("hostname", "username", "password") client.connect() try: sftp_client = client.client.open_sftp() # 自动拼接用户主目录路径 target_path = f"/home/{client.username}/screenshot.png" sftp_client.put("screenshot.png", target_path) print("上传成功") except Exception as e: print(f"上传失败:{str(e)}") finally: client.close()
内容的提问来源于stack exchange,提问作者wzack
相关产品推荐
相关产品推荐

