前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python3 paramiko 基于RSA私钥远程执行ssh、上传、下载文件

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

作者头像
Devops海洋的渔夫
发布2019-09-25 16:27:47
1.1K0
发布2019-09-25 16:27:47
举报
文章被收录于专栏:Devops专栏Devops专栏

介绍

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

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

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

使用pip3安装

pip3 install paramiko

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

文件结构

代码语言:javascript
复制
[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

代码语言:javascript
复制
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()

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019.09.25 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 介绍
  • 使用pip3安装
  • 文件结构
  • 封装示例代码 paramiko_test.py
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档