'NoneType' 对象没有属性 'open_session

'NoneType' object has no attribute 'open_session

我写了一个脚本来连接到 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

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

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")

with 自动关闭连接。无需明确关闭。