gpt4 book ai didi

python - SFTP : Copy/Download all files in a folder recursively from remote server

转载 作者:行者123 更新时间:2023-12-01 07:50:12 26 4
gpt4 key购买 nike

我得到了一个可以将文件从远程目录下载到本地目录的代码,但它给出了以下错误。

请解释该错误的含义以及解决方法。它在第二行显示问题。

我的代码

import paramiko, os
paramiko.util.log_to_file('/tmp/paramiko.log')
from stat import S_ISDIR
host = "ip"
port = 22
transport = paramiko.Transport((host, port))
password = "mypassword"
username = "username"
transport.connect(username = username, password = password)
sftp = paramiko.SFTPClient.from_transport(transport)
def sftp_walk(remotepath):
path=remotepath
files=[]
folders=[]
for f in sftp.listdir_attr(remotepath):
if S_ISDIR(f.st_mode):
folders.append(f.filename)
else:
files.append(f.filename)
if files:
yield path, files
for folder in folders:
new_path=os.path.join(remotepath,folder)
for x in sftp_walk(new_path):
yield x


for path,files in sftp_walk("." or '/remotepath/'):
for file in files:
#sftp.get(remote, local) line for dowloading.
sftp.get(os.path.join(os.path.join(path,file)), '/local path/')

我收到错误:

C:\Users\Rohan\PycharmProjects\untitled1\venv\Scripts\python.exe C:/Users/Rohan/PycharmProjects/untitled1/tyu.py
Traceback (most recent call last):
File "C:/Users/Rohan/PycharmProjects/untitled1/tyu.py", line 2, in <module>
paramiko.util.log_to_file('/tmp/paramiko.log')
File "C:\Users\Rohan\PycharmProjects\untitled1\venv\lib\site-packages\paramiko\util.py", line 252, in log_to_file
f = open(filename, "a")
FileNotFoundError: [Errno 2] No such file or directory: '/tmp/paramiko.log'

Process finished with exit code 1

最佳答案

import os
import pysftp
from stat import S_IMODE, S_ISDIR, S_ISREG

cnopts = pysftp.CnOpts()
cnopts.hostkeys = None
sftp=pysftp.Connection('192.168.X.X', username='username',password='password',cnopts=cnopts)

def get_r_portable(sftp, remotedir, localdir, preserve_mtime=False):
for entry in sftp.listdir(remotedir):
remotepath = remotedir + "/" + entry
localpath = os.path.join(localdir, entry)
mode = sftp.stat(remotepath).st_mode
if S_ISDIR(mode):
try:
os.mkdir(localpath)
except OSError:
pass
get_r_portable(sftp, remotepath, localpath, preserve_mtime)
elif S_ISREG(mode):
sftp.get(remotepath, localpath, preserve_mtime=preserve_mtime)

remote_path=input("enter the remote_path: ")
local_path=input("enter the local_path: ")

get_r_portable(sftp, remote_path, local_path, preserve_mtime=False)

关于python - SFTP : Copy/Download all files in a folder recursively from remote server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56268940/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com