python3 paramiko 基于RSA私钥远程执行ssh、上传、下载文件

本文介绍如何使用Python的Paramiko库配合RSA公钥,实现加密认证方式下远程服务器的连接、文件上传下载及命令执行。通过封装示例代码,展示如何利用Paramiko进行高效、安全的远程操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

介绍

paramiko 遵循SSH2协议,支持以加密和认证的方式,进行远程服务器的连接,可以实现远程文件的上传,下载或通过ssh远程执行命令。

项目地址:https://github.com/paramiko/paramiko

官方文档:http://docs.paramiko.org/

使用pip3安装

pip3 install paramiko

上一篇章已经讲诉了使用密码访问的方式 python3 paramiko 远程执行 ssh 命令、上传文件、下载文件 , 下面来看看封装使用RSA公钥访问的方式。

文件结构

[root@centos7 test_log]# tree paramiko-example/
paramiko-example/
├── file3.txt
├── file4.txt
├── paramiko_test.py
└── performance_rsa_4096

0 directories, 4 files
[root@centos7 test_log]# 

封装示例代码 paramiko_test.py

import paramiko
import os

class ParamikoHelper():

    def __init__(self,remote_ip, remote_ssh_port, private_key_file, ssh_username ):
        self.remote_ip = remote_ip
        self.remote_ssh_port = remote_ssh_port
        self.ssh_username = ssh_username
        self.private_key = paramiko.RSAKey.from_private_key_file(private_key_file) # 实例化一个私钥对象

    def connect_ssh(self):
        try:
            self.ssh = paramiko.SSHClient()
            self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            self.ssh.connect(hostname=self.remote_ip, port=self.remote_ssh_port, username=self.ssh_username,
                             pkey=self.private_key)
        except Exception as e:
            print(e)
        return self.ssh

    def close_ssh(self):
        try:
            self.ssh.close()
        except Exception as e:
            print(e)

    def exec_shell(self, shell):
        ssh = self.connect_ssh()
        try:
            stdin, stdout, stderr = ssh.exec_command(shell)
            return stdin, stdout, stderr
        except Exception as e:
            print(e)

    def sftp_put_file(self, file, local_dir, remote_dir):
        try:
            t = paramiko.Transport((self.remote_ip, self.remote_ssh_port))
            t.connect(username=self.ssh_username, pkey=self.private_key)
            sftp = paramiko.SFTPClient.from_transport(t)
            sftp.put(os.path.join(local_dir, file), remote_dir)
            t.close()
        except Exception:
            print("connect error!")

    def sftp_get_file(self, file, local_dir, remote_dir):
        try:
            t = paramiko.Transport((self.remote_ip, self.remote_ssh_port))
            t.connect(username=self.ssh_username, pkey=self.private_key)
            sftp = paramiko.SFTPClient.from_transport(t)
            sftp.get(remote_dir, os.path.join(local_dir, file))
            t.close()
        except Exception:
            print("connect error!")


def main():
    remote_ip = '192.168.196.134'
    remote_ssh_port = 22
    ssh_username = 'root'
    private_key_file = 'performance_rsa_4096' # RSA私钥
    ph = ParamikoHelper(remote_ip=remote_ip,remote_ssh_port=remote_ssh_port,private_key_file=private_key_file,ssh_username=ssh_username)

    # 远程执行ssh命令
    shell = "df -h | grep dev"
    stdin, stdout, stderr = ph.exec_shell(shell)
    for line in stdout.readlines():
        print(line)
    ph.close_ssh()

    # 上传文件file4.txt到远程服务器上
    file = 'file4.txt'
    remote_dir = '/root/test_log/' + file
    local_dir = os.getcwd()
    ph.sftp_put_file(file=file, local_dir=local_dir, remote_dir=remote_dir)

    # 下载文件file3.txt
    file = 'file3.txt'
    remote_dir = '/root/test_log/' + file
    local_dir = os.getcwd()
    ph.sftp_get_file(file=file, local_dir=local_dir, remote_dir=remote_dir)

if __name__ == '__main__':
    main()
13423234-0e3934319aa622f6.png
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

海洋的渔夫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值