使用python递归下载Linux主机文件夹下的文件
一、示例代码以及说明
1. 建立连接
创建一个ssh连接,输入为ip、端末号、用户名、密码
import paramiko
# 创建sftp连接
def Create_Connection(host_ip, host_port, username, password):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(host_ip, host_port, username=username, password=password)
return ssh
2. 文件拷贝
方法大概是:收件建立一个ftp连接,然后递归获取指定文件夹下的所有文件,最后对于每一个文件在Windows系统的本地创建同名文件夹,再进行拷贝即可。
import os
def download_folder_from_host(ssh, local_path, host_path):
# 建立连接
ftp = ssh.open_sftp()
print("start copy folder from " + host_path + " to " + local_path + " :")
# 递归取得指定host路径下的所有文件和文件夹
def __get_all_files_in_remote_dir(ftp, remote_path):
all_files = list()
if remote_path[-1] == '/':
remote_path = remote_path[0:-1]
files = ftp.listdir_attr(remote_path)
for i_file in files:
filename = remote_path + '/' + i_file.filename
if S_ISDIR(i_file.st_mode):
all_files.extend(__get_all_files_in_remote_dir(ftp, filename))
else:
all_files.append((filename, filename.replace(remote_path, "").replace("/", "")))
return all_files
all_files = __get_all_files_in_remote_dir(ftp, host_path)
for file, fileName in all_files:
# print(file, fileName)
try:
# 对于每一个host
os.makedirs(local_path+file.replace(host_path, "").replace(fileName, ""))
except FileExistsError:
pass
ftp.get(file, local_path+file.replace(host_path, ""))
print(file, "=>", local_path+file.replace(host_path, ""))
print("OK")
# 关闭连接
ftp.close()
示例代码如下:
local_path = r"./test"
host_path = "/home/builder/test"
conn = Create_Connection("127.0.0.1", 10022, "wyl", "12345678")
download_folder_from_host(conn, local_path, host_path)
总结
本文通过使用python编程语言以及paramiko库,实现了从Linux Host端下载文件到本地,通过递归的方法将指定文件夹下的全部文件复制到本地,方便后续的处理,希望对你有所帮助,谢谢阅读。