python使用FTP/SFTP发送文件,连接ssh

目录

1. FTP 

2. SFTP 

3.  Paramiko库


1. FTP 

from ftplib import FTP

def upload_file_to_ftp(server, port, username, password, local_file_path, remote_directory, remote_file_name):
    # 初始化FTP对象
    ftp = FTP()

    try:
        # 连接到FTP服务器
        ftp.connect(server, port)
        # 登录到FTP服务器
        ftp.login(username, password)

        # 打印FTP欢迎消息
        print(ftp.getwelcome())

        # 切换到指定的远程目录(不切换到路径下也可以,直接拼接好绝对路径,目录+文件名)
        ftp.cwd(remote_directory)

        # 打开本地文件
        with open(local_file_path, 'rb') as file:
            # 使用STOR命令将文件上传到FTP服务器
            ftp.storbinary(f'STOR {remote_file_name}', file)

        print(f'{remote_file_name} uploaded to {remote_directory} successfully.')

    except Exception as e:
        print(f'An error occurred: {e}')

    finally:
        # 关闭FTP连接
        ftp.quit()

# FTP服务器信息
ftp_server = 'your.ftp.server.address'
ftp_port = 21  # FTP默认端口是21
ftp_username = 'your_username'
ftp_password = 'your_password'

# 本地文件信息
local_file = '/path/to/your/local/file.txt'

# 远程目录和文件名
remote_directory = '/opt/test'
remote_file_name = 'file.txt'  # 可以根据需要更改上传后的文件名

# 上传文件
upload_file_to_ftp(ftp_server, ftp_port, ftp_username, ftp_password, local_file, remote_directory, remote_file_name)

2. SFTP 

import paramiko

def upload_file_via_sftp(local_file_path, remote_file_path, host, port, username, password):
    """
    使用SFTP上传文件到远程服务器

    :param local_file_path: 本地文件的路径
    :param remote_file_path: 远程服务器上的目标文件路径
    :param host: 远程服务器的主机地址
    :param port: SSH端口,默认是22
    :param username: 登录远程服务器的用户名
    :param password: 登录远程服务器的密码
    """
    # 创建SSH客户端对象
    ssh = paramiko.SSHClient()
    # 允许连接不在know_hosts文件中的主机
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    try:
        # 连接远程服务器
        ssh.connect(host, port, username, password)
        # 打开SFTP会话
        sftp = ssh.open_sftp()
        try:
            # 上传文件,将本地文件上传到远程指定路径
            sftp.put(local_file_path, remote_file_path)
            print(f"文件 {local_file_path} 已成功上传到 {remote_file_path}")
        except Exception as e:
            print(f"文件上传出现错误: {e}")
        finally:
            # 关闭SFTP会话
            sftp.close()
    except Exception as e:
        print(f"连接远程服务器出现错误: {e}")
    finally:
        # 关闭SSH客户端连接
        ssh.close()

3.  Paramiko库

Paramiko 是一个用于实现 SSH2 协议的 Python 库。在 Python 程序中进行安全的远程连接、执行命令、传输文件等操作,为自动化运维、远程服务器管理等场景提供了方便的工具。

eg:使用用户名密码连接ssh,执行命令

def ssh_connection_exec(hostname, username, password, command):
    """
    用户名,密码连接
    @param hostname: 
    @param username: 
    @param password: 
    @param command: 命令
    @return: 
    """
    client = None
    try:
        # 创建SSH客户端对象
        client = paramiko.SSHClient()

        # 自动添加主机密钥,如果之前没有连接过的ip,会出现选择yes或者no,自动选择yes
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())

        # 连接主机 超时时间为5S
        client.connect(hostname, username=username, password=password, timeout=10)

        # 执行命令
        stdin, stdout, stderr = client.exec_command(command)

        # 检查命令执行结果
        if stdout.channel.recv_exit_status() == 0:
            print("SSH连接成功,主机可联通.")
        else:
            return False, f"SSH连接成功,但主机不可联通.{stderr.read()}"

        client.close()
        content = stdout.read().decode('utf-8')
        return True, content

    except paramiko.AuthenticationException:
        return False, "SSH连接失败,认证错误。"
    except paramiko.SSHException as e:
        return False, "SSH连接失败:" + str(e)
    except Exception as e:
        return False, "发生未知错误:" + str(e)
    finally:
        if client:
            client.close()

使用公私钥连接ssh,执行命令

def ssh_connection_exec_key(hostname, username, command):
    try:
        # 读取本地私钥
        private_key_path = os.path.join(BASE_DIR, "conf", "id_rsa")
        print(f"私钥位置:{private_key_path}")

        private_key = paramiko.RSAKey.from_private_key_file(private_key_path)

        # 创建SSH对象
        ssh = paramiko.SSHClient()

        # 允许连接不在know_hosts文件中的主机
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # 连接服务器
        ssh.connect(hostname=hostname, port=22, username=username, pkey=private_key, timeout=10)
        print("pub-key连接成功")

        # 执行命令
        stdin, stdout, stderr = ssh.exec_command(command)

        # 检查命令执行结果
        if stdout.channel.recv_exit_status() == 0:
            print("SSH连接成功,主机可联通.")
        else:
            print(stderr.read())
            return False, "SSH连接成功,但主机不可联通."

        ssh.close()
        content = stdout.read().decode('utf-8')
        return True, content

    except paramiko.AuthenticationException:
        return False, "SSH连接失败,认证错误。"
    except paramiko.SSHException as e:
        return False, "SSH连接失败:" + str(e)
    except Exception as e:
        logger.error(traceback.format_exc())
        return False, "发生未知错误:" + str(e)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值