'NoneType'对象没有属性'open_session

时间:2019-05-22 05:58:03

标签: python-3.x pysftp

我写了一个脚本来用python连接到sftp服务器,但是它在下面显示了此错误,我不理解。请帮助我修复错误

import pysftp

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None

with pysftp.Connection(host="127.0.0.1", username="new34",password="password",cnopts=cnopts) as srv:
    print("connection successful")

# Get the directory and file listing
data = srv.listdir()

srv.put("testfile.txt")


# Closes the connection
srv.close()

# Prints out the directories and files, line by line
for i in data:
    print(i)

它显示以下错误;请帮助修复该错误

C:\Users\Rohan\PycharmProjects\untitled1\venv\Scripts\python.exe C:/Users/Rohan/PycharmProjects/untitled1/yu.py
C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\pysftp\__init__.py:61: UserWarning: Failed to load HostKeys from C:\Users\Rohan\.ssh\known_hosts.  You will need to explicitly load HostKeys (cnopts.hostkeys.load(filename)) or disableHostKey checking (cnopts.hostkeys = None).
  warnings.warn(wmsg, UserWarning)
Traceback (most recent call last):
connection successful
  File "C:/Users/Rohan/PycharmProjects/untitled1/yu.py", line 10, in <module>
    data = srv.listdir()
  File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\pysftp\__init__.py", line 591, in listdir
    self._sftp_connect()
  File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\pysftp\__init__.py", line 205, in _sftp_connect
    self._sftp = paramiko.SFTPClient.from_transport(self._transport)
  File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\paramiko\sftp_client.py", line 164, in from_transport
    chan = t.open_session(
AttributeError: 'NoneType' object has no attribute 'open_session'

Process finished with exit code 1

1 个答案:

答案 0 :(得分:0)

您的代码存在缩进问题。 试试这个,

with pysftp.Connection(host="127.0.0.1", username="new34",password="password",cnopts=cnopts) as srv: print("connection successful") # Get the directory and file listing data = srv.listdir() srv.put("testfile.txt") 自动关闭连接。无需明确关闭。