使用python递归下载Linux主机文件夹下的文件

使用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端下载文件到本地,通过递归的方法将指定文件夹下的全部文件复制到本地,方便后续的处理,希望对你有所帮助,谢谢阅读。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值