Python | 将本地文件上传到远程服务器

在Python中,可以使用paramiko库来通过SSH进行文件的传输。

首先,你需要安装paramiko库,可以使用以下命令进行安装:

pip install paramiko

然后,你可以使用以下Python脚本进行文件传输:

此脚本使用SFTP协议进行文件传输。在SFTP的上下文中,你可以使用put方法将本地文件上传到远程服务器。

import paramiko

def upload_file(local_path, remote_path, hostname, username, password):
    # 创建 SSH 客户端
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

    try:
        # 连接到远程服务器
        client.connect(hostname, username=username, password=password)

        # 使用 SFTP 协议创建一个传输通道
        with client.open_sftp() as sftp:
            # 上传本地文件到远程服务器
            sftp.put(local_path, remote_path)
            print(f"文件 {local_path} 已成功上传到 {remote_path}")

    except Exception as e:
        print(f"上传文件时发生错误: {e}")

    finally:
        # 关闭 SSH 连接
        client.close()

# 本地文件路径
local_file_path = "/path/to/local/file.txt"

# 远程服务器信息
remote_server_hostname = "your_remote_server_ip"
remote_server_username = "your_username"
remote_server_password = "your_password"

# 远程文件路径
remote_file_path = "/path/to/remote/file.txt"

# 调用函数进行文件上传
upload_file(local_file_path, remote_file_path, remote_server_hostname, remote_server_username, remote_server_password)

确保替换示例中的 your_remote_server_ip、your_username、your_password 以及本地和远程文件路径为你实际使用的值。

此外,建议使用 SSH 密钥而不是密码进行身份验证,以提高安全性。

使用ssh.exec_command()执行指令,如下

rename_folder_command = f'mv today_folder_path yesterday_date'
ssh.exec_command(rename_folder_command)
posted @   槑孒  阅读(649)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
历史上的今天:
2022-11-13 jquery-一行代码解决跨域问题 | 不支持post请求
2022-11-13 chrome浏览器 开发者工具F12中某网站的sources下的源码如何批量保存
点击右上角即可分享
微信分享提示