当前位置: 代码网 > it编程>前端脚本>Python > Python Paramiko创建文件目录并上传文件详解

Python Paramiko创建文件目录并上传文件详解

2024年10月23日 Python 我要评论
引言在网络运维和自动化领域,ssh(secure shell)协议是连接和管理远程服务器的常用手段。而paramiko是一个用于进行ssh2会话的python库,它支持加密、认证和文件传输等功能。使用

引言

在网络运维和自动化领域,ssh(secure shell)协议是连接和管理远程服务器的常用手段。而paramiko是一个用于进行ssh2会话的python库,它支持加密、认证和文件传输等功能。使用paramiko,可以方便地实现远程命令执行、文件上传下载等操作。本文旨在详细指导新手朋友如何使用python的paramiko库来创建远程文件目录并上传文件。

一、安装paramiko

首先,确保你已经安装了paramiko库。如果没有安装,可以通过pip轻松完成:

pip install paramiko

安装完成后,在python脚本中导入所需的模块:

import paramiko

二、创建ssh连接

在开始任何操作之前,需要创建一个ssh客户端实例,并配置相关参数。以下是一个基本示例:

ssh_client = paramiko.sshclient()  
ssh_client.set_missing_host_key_policy(paramiko.autoaddpolicy())  # 自动添加主机密钥

接下来,使用服务器的ip地址、端口号、用户名和密码来连接到远程服务器:

ssh_client.connect(hostname='your_server_ip', port=22, username='your_username', password='your_password')

三、创建远程文件目录

一旦连接成功,你就可以通过执行ssh命令来创建文件目录。以下是一个简单的示例,展示如何创建一个名为my_directory的新目录:

command = "mkdir my_directory"  
stdin, stdout, stderr = ssh_client.exec_command(command)  
print("directory created:", stdout.read().decode())

另外,你也可以通过sftp会话来创建目录,paramiko提供了一个sftp客户端,可以很方便地进行文件传输和目录管理。以下是一个通过sftp创建目录的示例:

sftp_client = ssh_client.open_sftp()  
try:  
    remote_path = '/path/to/your/folder/subfolder'  
    sftp_client.makedirs(remote_path)  # 这里会自动创建多级目录  
except ioerror as e:  
    print(f"error creating remote directory: {e}")  
finally:  
    sftp_client.close()  
    ssh_client.close()

四、上传文件

要上传文件,可以使用paramiko的sftpclient类的put()方法。该方法接受两个参数:本地文件路径和远程文件路径。以下示例将本地文件/tmp/file.txt上传到远程服务器的/home/user/目录:

sftp_client = ssh_client.open_sftp()  
try:  
    local_file_path = '/tmp/file.txt'  
    remote_file_path = '/home/user/file.txt'  
    sftp_client.put(local_file_path, remote_file_path)  
    print('file uploaded successfully')  
except filenotfounderror:  
    print("local file not found!")  
except permissionerror:  
    print("no permission to upload the file!")  
except exception as e:  
    print("an error occurred:", str(e))  
finally:  
    sftp_client.close()  
    ssh_client.close()

在实际操作过程中,可能会遇到各种异常,比如文件不存在、权限问题等。因此,合理地处理异常是非常重要的。

五、下载文件

要下载文件,可以使用paramiko的sftpclient类的get()方法。该方法接受两个参数:远程文件路径和本地文件路径。以下示例将远程服务器的/home/user/file.txt文件下载到本地的/tmp/目录:

sftp_client = ssh_client.open_sftp()  
try:  
    remote_file_path = '/home/user/file.txt'  
    local_file_path = '/tmp/file.txt'  
    sftp_client.get(remote_file_path, local_file_path)  
    print('file downloaded successfully')  
except filenotfounderror:  
    print("remote file not found!")  
except permissionerror:  
    print("no permission to download the file!")  
except exception as e:  
    print("an error occurred:", str(e))  
finally:  
    sftp_client.close()  
    ssh_client.close()

六、上传和下载文件夹

要上传文件夹,可以使用paramiko的sftpclient类的put()方法来逐个上传文件,也可以使用put_recursive()方法来递归上传文件夹。以下示例将本地文件夹/tmp/folder递归上传到远程服务器的/home/user/目录:

import os  
  
def upload_folder(local_folder_path, remote_folder_path):  
    sftp_client = ssh_client.open_sftp()  
    try:  
        for root, dirs, files in os.walk(local_folder_path):  
            remote_current_path = remote_folder_path + root[len(local_folder_path):].strip(os.sep)  
            if not sftp_client.listdir(remote_current_path):  
                sftp_client.makedirs(remote_current_path)  
            for file in files:  
                local_file_path = os.path.join(root, file)  
                remote_file_path = os.path.join(remote_current_path, file)  
                sftp_client.put(local_file_path, remote_file_path)  
        print('folder uploaded successfully')  
    except exception as e:  
        print("an error occurred:", str(e))  
    finally:  
        sftp_client.close()  
        ssh_client.close()  
  
upload_folder('/tmp/folder', '/home/user/')

要下载文件夹,可以使用paramiko的sftpclient类的get()方法来逐个下载文件,也可以使用get_recursive()方法来递归下载文件夹。以下示例将远程服务器的/home/user/folder文件夹递归下载到本地的/tmp/目录:

import os  
  
def download_folder(remote_folder_path, local_folder_path):  
    sftp_client = ssh_client.open_sftp()  
    try:  
        if not os.path.exists(local_folder_path):  
            os.makedirs(local_folder_path)  
        for filename in sftp_client.listdir(remote_folder_path):  
            remote_file_path = os.path.join(remote_folder_path, filename)  
            local_file_path = os.path.join(local_folder_path, filename)  
            if sftp_client.stat(remote_file_path).st_mode & 0o170000 == 0o040000:  # 如果是文件夹  
                download_folder(remote_file_path, local_file_path)  
            else:  
                sftp_client.get(remote_file_path, local_file_path)  
        print('folder downloaded successfully')  
    except exception as e:  
        print("an error occurred:", str(e))  
    finally:  
        sftp_client.close()  
        ssh_client.close()  
  
download_folder('/home/user/folder', '/tmp/')

七、异常处理和高级功能

在实际操作过程中,可能会遇到各种异常,比如文件不存在、权限问题等。因此,合理地处理异常是非常重要的。此外,在某些场景下,网络不稳定或者文件较大时,断点续传和错误重试功能就显得尤为重要。

你可以通过设置put方法的resumable参数为true来实现断点续传(需要注意的是,paramiko本身并不直接支持断点续传,这里仅作为一个可能的扩展思路),并通过循环和异常处理来实现错误重试。

以下是一个带有错误重试机制的上传文件示例:

import time  
  
def upload_file_with_retry(local_file_path, remote_file_path, retries=3, delay=2):  
    sftp_client = ssh_client.open_sftp()  
    attempt = 0  
    while attempt < retries:  
        try:  
            sftp_client.put(local_file_path, remote_file_path)  
            print('file uploaded successfully')  
            return  
        except exception as e:  
            print(f"attempt {attempt + 1} failed: {str(e)}")  
            attempt += 1  
            if attempt < retries:  
                time.sleep(delay)  
        finally:  
            sftp_client.close()  
    ssh_client.close()  
    print('failed to upload file after retries')  
  
upload_file_with_retry('/tmp/file.txt', '/home/user/file.txt')

八、总结

通过本文的指导,你现在应该能够使用python的paramiko库来创建远程文件目录并上传文件。这些技能不仅能够提高你的工作效率,还能够让你在自动化运维的道路上更进一步。记得在实际操作中多加练习,以便更好地掌握这些有用的工具。

此外,敏感信息如服务器地址、用户名和密码应妥善保管,不应在公开场合泄露。

到此这篇关于python paramiko创建文件目录并上传文件详解的文章就介绍到这了,更多相关python paramiko创建文件目录内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com