Python3.6.5使用pysftp模块报错AttributeError:无Connection属性求解决方案
AttributeError: module 'pysftp' has no attribute 'Connection' Issue in Python 3.6.5 Hey there! Let's break down what's going on with your pysftp problem, then cover fixes and more reliable alternatives since pysftp has been unmaintained since 2016.
Why This Error Happens
That AttributeError typically stems from two common issues:
- Local file name conflict: If you have a local script named
pysftp.py(or a compiledpysftp.pycfile), Python will import this local file instead of the official package you installed. This means you're not loading the real pysftp library, so theConnectionclass is missing. - Corrupted or incomplete installation: Even though some users report pysftp 0.2.9 works on Python 3.6, a botched install can leave out critical components needed for the
Connectionclass.
Quick Fixes for Pysftp
Check for file name clashes
Rename any local file namedpysftp.py(or.pyc) to something else (likemy_sftp_script.py). This ensures Python pulls the correct package from your site-packages folder instead of your local script.Reinstall pysftp properly
Uninstall the existing package and reinstall the 0.2.9 version explicitly:pip uninstall pysftp -y pip install pysftp==0.2.9After reinstalling, test your original code again to see if the connection works.
Better Long-Term Alternative: Use Paramiko
Since pysftp hasn't been updated in over 7 years, it's not ideal for production code. Paramiko is the actively maintained underlying library that pysftp relies on—it fully supports Python 3.6+ and offers a more robust, secure API.
Here's how to rewrite your SFTP connection code with Paramiko:
import paramiko # Replace with your connection details host = "your_host" username = "your_username" password = "your_password" try: # Initialize SSH client ssh_client = paramiko.SSHClient() # Automatically add unknown host keys (adjust this for production!) ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # Establish connection ssh_client.connect(host, username=username, password=password) # Open SFTP session sftp = ssh_client.open_sftp() print("Connection successfully established ... ") # Example: Upload a file # sftp.put("local_file_path", "remote_file_path") # Example: Download a file # sftp.get("remote_file_path", "local_file_path") finally: # Clean up connections if 'sftp' in locals(): sftp.close() ssh_client.close()
Note: For production, avoid AutoAddPolicy()—instead, load trusted host keys from a file to boost security.
内容的提问来源于stack exchange,提问作者J.Delannoy

