使用Python中的PysFTP上传OS.Listdir列出的所有文件到SFTP服务器

发布于 2025-02-12 18:30:52 字数 1465 浏览 1 评论 0原文

我正在尝试从c:/test/文件夹上传文件。 代码:

import pysftp
import os
host = host
port = 22
username = username
password= pass
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
try:
  conn = pysftp.Connection(host=host,port=port,username=username, password=password, cnopts=cnopts)
  print("connection established successfully")
except:
  print('failed to establish connection to targeted server')
files=os.listdir('C:/Test/')
with conn.cd('/'):
    for file in files:
            try:
                conn.put(file)
                print('uploaded file successfully: ',file)
            except:
                print('failed to upload file: ',file)

我会遇到错误:

“无法上传文件”或“非典型对象没有属性时间”

但此代码可用于一个文件。我在做什么错?

This is Error:
failed to upload file:  Test.pdf
Exception ignored in: <function Connection.__del__ at 0x000001C180B71B40>
Traceback (most recent call last):
  File "C:\Python\lib\site-packages\pysftp\__init__.py", line 1013, in __del__
  File "C:\Python\lib\site-packages\pysftp\__init__.py", line 785, in close
  File "C:\Python\lib\site-packages\paramiko\sftp_client.py", line 195, in close
  File "C:\Python\lib\site-packages\paramiko\channel.py", line 671, in close
  File "C:\Python\lib\site-packages\paramiko\transport.py", line 1901, in _send_user_message
AttributeError: 'NoneType' object has no attribute 'time'

I am trying to upload files from C:/Test/ folder.
Code:

import pysftp
import os
host = host
port = 22
username = username
password= pass
cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
try:
  conn = pysftp.Connection(host=host,port=port,username=username, password=password, cnopts=cnopts)
  print("connection established successfully")
except:
  print('failed to establish connection to targeted server')
files=os.listdir('C:/Test/')
with conn.cd('/'):
    for file in files:
            try:
                conn.put(file)
                print('uploaded file successfully: ',file)
            except:
                print('failed to upload file: ',file)

And I am getting error:

"failed to upload file" or "NoneType object has no attribute time"

But this code works fine for one file. What am I doing wrong?

This is Error:
failed to upload file:  Test.pdf
Exception ignored in: <function Connection.__del__ at 0x000001C180B71B40>
Traceback (most recent call last):
  File "C:\Python\lib\site-packages\pysftp\__init__.py", line 1013, in __del__
  File "C:\Python\lib\site-packages\pysftp\__init__.py", line 785, in close
  File "C:\Python\lib\site-packages\paramiko\sftp_client.py", line 195, in close
  File "C:\Python\lib\site-packages\paramiko\channel.py", line 671, in close
  File "C:\Python\lib\site-packages\paramiko\transport.py", line 1901, in _send_user_message
AttributeError: 'NoneType' object has no attribute 'time'

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

山有枢 2025-02-19 18:30:52

os.listdir返回仅文件名。您必须将完整路径传递到 nofollow noreferrer“> pysftpppppppppppppppppppppppppppp Connection。放置

如果您不吞噬实际例外,您会很容易地了解到:

Traceback (most recent call last):
  File "test.py", line 19, in <module>
    conn.put(file)
  File "C:\...\Python\Python39\lib\site-packages\pysftp\__init__.py", line 363, in put
    sftpattrs = self._sftp.put(localpath, remotepath, callback=callback,
  File "C:\...\Python\Python39\lib\site-packages\paramiko\sftp_client.py", line 757, in put
    file_size = os.stat(localpath).st_size
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.log'  

代码应该是:

localpath = "C:/Test/"
files = os.listdir(localpath)
with conn.cd("/"):
    for file in files:
        if file[-4:]=='.log':
            try:
                conn.put(os.path.join(localpath, file))
                print('uploaded file successfully: ',file)
            except:
                print('failed to upload file: ',file)

或简单地将工作目录更改为源路径:

os.chdir("C:/Test/")
files = os.listdir(".")
with conn.cd("/"):
    for file in files:
        if file[-4:]=='.log':
            try:
                conn.put(file)
                print('uploaded file successfully: ',file)
            except:
                print('failed to upload file: ',file)

义务警告:

  • do not de设置<代码> cnopts.hostkeys =无,除非您不关心安全性。有关正确的解决方案,请参见使用pysftp

  • 尽管这些天,但您不应使用PysFTP,因为它已经死了。直接使用Paramiko。参见 pysftp vs. paramiko 。。

The os.listdir returns file names only. You have to pass full path to the pysftp Connection.put.

You would easily learn that had you not swallowed the actual exception:

Traceback (most recent call last):
  File "test.py", line 19, in <module>
    conn.put(file)
  File "C:\...\Python\Python39\lib\site-packages\pysftp\__init__.py", line 363, in put
    sftpattrs = self._sftp.put(localpath, remotepath, callback=callback,
  File "C:\...\Python\Python39\lib\site-packages\paramiko\sftp_client.py", line 757, in put
    file_size = os.stat(localpath).st_size
FileNotFoundError: [WinError 2] The system cannot find the file specified: 'test.log'  

The code should be like:

localpath = "C:/Test/"
files = os.listdir(localpath)
with conn.cd("/"):
    for file in files:
        if file[-4:]=='.log':
            try:
                conn.put(os.path.join(localpath, file))
                print('uploaded file successfully: ',file)
            except:
                print('failed to upload file: ',file)

Or simply change the working directory to the source path:

os.chdir("C:/Test/")
files = os.listdir(".")
with conn.cd("/"):
    for file in files:
        if file[-4:]=='.log':
            try:
                conn.put(file)
                print('uploaded file successfully: ',file)
            except:
                print('failed to upload file: ',file)

Obligatory warnings:

  • Do not set cnopts.hostkeys = None, unless you do not care about security. For the correct solution see Verify host key with pysftp.

  • Though these days, you should not use pysftp, as it is dead. Use Paramiko directly instead. See pysftp vs. Paramiko.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文