python3 paramiko 远程执行 ssh 命令、上传文件、下载文件

2024-08-21 04:18

本文主要是介绍python3 paramiko 远程执行 ssh 命令、上传文件、下载文件,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

在win10的系统下,本来想要python3直接调用ansible库进行远程执行的,但是很可惜,ansible是基于linux系统的ssh服务进行远程调用,不太兼容windows。
那么下面来使用paramiko库,直接手写一个ssh远程调用。

介绍

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

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

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

使用pip3安装

pip3 install paramiko

安装过程如下:

D:\pythonProject\locust_auto_test>pip3 install paramiko
Collecting paramikoUsing cached https://files.pythonhosted.org/packages/17/9f/7430d1ed509e195d5a5bb1a2bda6353a4aa64eb95491f198a17c44e2075c/paramiko-2.5.0-py2.py3-none-any.whl
Collecting bcrypt>=3.1.3 (from paramiko)Downloading https://files.pythonhosted.org/packages/09/91/1b9e566c9aafe40eb89b31a7d322c7c070a3249bd2f3e50c8828fe4418d7/bcrypt-3.1.6-cp37-cp37m-win_amd64.whl
Requirement already satisfied: cryptography>=2.5 in d:\python37\lib\site-packages (from paramiko) (2.7)
Collecting pynacl>=1.0.1 (from paramiko)Using cached https://files.pythonhosted.org/packages/fc/e7/179847c0dce637c59cea416c75b8de1ec1e862358c7369ad99c1fad00158/PyNaCl-1.3.0-cp37-cp37m-win_amd64.whl
Requirement already satisfied: cffi>=1.1 in d:\python37\lib\site-packages (from bcrypt>=3.1.3->paramiko) (1.12.1)
Requirement already satisfied: six>=1.4.1 in d:\python37\lib\site-packages (from bcrypt>=3.1.3->paramiko) (1.12.0)
Requirement already satisfied: asn1crypto>=0.21.0 in d:\python37\lib\site-packages (from cryptography>=2.5->paramiko) (0.24.0)
Requirement already satisfied: pycparser in d:\python37\lib\site-packages (from cffi>=1.1->bcrypt>=3.1.3->paramiko) (2.19)
Installing collected packages: bcrypt, pynacl, paramiko
Successfully installed bcrypt-3.1.6 paramiko-2.5.0 pynacl-1.3.0D:\pythonProject\locust_auto_test>

测试是否安装成功,如下:

D:\pythonProject\locust_auto_test>ipython3
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: import paramikoIn [2]: 

可以看到导入并没有出错,所以下面可以正常使用这个库了。

在本次实验中,最核心的功能就是远程执行ssh命令,所以首先来实验一下这个功能。

使用ipython3远程执行ssh命令

D:\pythonProject\locust_auto_test>ipython3
Python 3.7.1 (v3.7.1:260ec2c36a, Oct 20 2018, 14:57:15) [MSC v.1915 64 bit (AMD64)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.2.0 -- An enhanced Interactive Python. Type '?' for help.In [1]: import paramiko# 设置ssh访问信息
In [2]: remote_ip = '192.168.196.129'In [3]: remote_ssh_port = 22In [5]: ssh_password = '********'In [6]: ssh_username = 'root'In [7]: ssh = paramiko.SSHClient()# 设置连接策略
In [8]: ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())# ssh连接服务器
In [9]: ssh.connect( hostname = remote_ip, port = remote_ssh_port, username = ssh_username, password = ssh_password )# 远程ssh执行shell命令
In [10]: stdin, stdout, stderr = ssh.exec_command("df -h | grep dev")# 打印查看磁盘信息的结果
In [11]: print(stdout.readlines())
['/dev/mapper/centos-root   17G  9.7G  7.3G  58% /\n', 'devtmpfs                 899M     0  899M   0% /dev\n', 'tmpfs                    911M     0  911M   0% /dev/shm\n',
'/dev/sda1               1014M  142M  873M  14% /boot\n']In [12]: # 执行完毕之后,结果只会打印一次
In [14]: stdin, stdout, stderr = ssh.exec_command("df -h | grep dev")In [15]: for line in stdout.readlines():...:     print(line)...: 
/dev/mapper/centos-root   17G  9.7G  7.3G  58% /devtmpfs                 899M     0  899M   0% /devtmpfs                    911M     0  911M   0% /dev/shm/dev/sda1               1014M  142M  873M  14% /boot## 执行一个存在等待时长的shell命令
In [24]: stdin, stdout, stderr = ssh.exec_command("df -h | grep dev && echo '123' && sleep 10 && echo 'sleep complete'")## 发现应该是在执行打印的时候,才是真正执行shell命令。
In [25]: for line in stdout.readlines():...:     print(line)...: 
/dev/mapper/centos-root   17G  9.7G  7.3G  58% /devtmpfs                 899M     0  899M   0% /devtmpfs                    911M     0  911M   0% /dev/shm/dev/sda1               1014M  142M  873M  14% /boot123sleep completeIn [26]: # 执行一个查看日志的远程ssh命令
In [11]: stdin, stdout, stderr = ssh.exec_command("tail -f /root/test_log/test.log")In [12]: for line in stdout.readlines():...:     print(line)...: # 发现就算写入新的信息进去,是不会持续打印出新的信息的。
# 也就是验证了这个ssh执行时一次性的执行结果。# 关闭ssh连接
In [16]: ssh.close()

上传文件功能

In [2]: import osIn [10]: import paramiko## 设置sftp连接信息
In [11]: remote_ip = '192.168.196.129'In [12]: remote_ssh_port = 22In [13]: ssh_password = '***********'In [14]: ssh_username = 'root'## 创建sftp连接
In [16]: t = paramiko.Transport((remote_ip, remote_ssh_port))In [17]: t.connect(username=ssh_username, password=ssh_password)In [18]: sftp = paramiko.SFTPClient.from_transport(t)## 执行上传sftp
In [26]: sftp.put('D:\\pythonProject\\locust_auto_test\\paramiko_test\\file1.txt', '/root/test_log/file1.txt')
Out[26]: <SFTPAttributes: [ size=18 uid=0 gid=0 mode=0o100644 atime=1560329096 mtime=1560329096 ]>In [27]: ## 关闭sftp连接
In [28]: t.close()

到远程服务器查看上传好的文件,如下:

[root@centos7 test_log]# ls
file1.txt
[root@centos7 test_log]# cat file1.txt 
测试上传文件[root@centos7 test_log]# 
[root@centos7 test_log]# 

执行下载文件

首先在远程Centos7将file1.txt文件拷贝一份为file2.txt,用于下载该文件。

[root@centos7 test_log]# cp file1.txt file2.txt 
[root@centos7 test_log]# 
[root@centos7 test_log]# ls
file1.txt  file2.txt
[root@centos7 test_log]# 

执行下载文件功能如下:

## 创建sftp连接
In [29]: t = paramiko.Transport((remote_ip, remote_ssh_port))In [30]: t.connect(username=ssh_username, password=ssh_password)In [31]: sftp = paramiko.SFTPClient.from_transport(t)## 通过sftp查看远程服务器该路径有什么文件
In [32]: sftp.listdir('/root/test_log')
Out[32]: ['file1.txt', 'file2.txt']## 设置本地路径
In [35]: local_dir = 'D:\\pythonProject\\locust_auto_test\\paramiko_test\\file2.txt'## 设置远程路径
In [36]: remote_dir = '/root/test_log/file2.txt'## 下载远程路径的文件到本地路径
In [37]: sftp.get(remote_dir,local_dir)## 查看本地路径是否已有file2.txt,可以看到已经成功下载下来了。
In [38]: os.listdir(os.getcwd())
Out[38]: ['file1.txt', 'file2.txt', 'test1.py']

上面我写windows下的路径都是直接写了个全路径,是为了方便理解,下面可以使用命令来设置这些路径。

In [41]: local_dir = os.path.join(os.getcwd(),'file2.txt')In [42]: sftp.get(remote_dir,local_dir)In [43]: os.listdir(os.getcwd())
Out[43]: ['file1.txt', 'file2.txt', 'test1.py']In [44]: 

当时由于windows与linux获取当前路径的拼接方式不同,所以linux路径我还是直接使用字符串写远程路径的方式。

上面基本上已经将功能都完成了,下一步就可以将这些方法都封装到一个工具类中。

封装工具类方法

import paramiko
import osclass ParamikoHelper():def __init__(self,remote_ip, remote_ssh_port, ssh_password, ssh_username ):self.remote_ip = remote_ipself.remote_ssh_port = remote_ssh_portself.ssh_password = ssh_passwordself.ssh_username = ssh_usernamedef 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,password=self.ssh_password)except Exception as e:print(e)return self.sshdef 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, stderrexcept 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, password=self.ssh_password)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, password=self.ssh_password)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.129'remote_ssh_port = 22ssh_password = '**************'ssh_username = 'root'ph = ParamikoHelper(remote_ip=remote_ip,remote_ssh_port=remote_ssh_port,ssh_password=ssh_password,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()# 上传文件file2.txt到远程服务器上file = 'file2.txt'remote_dir = '/root/test_log/' + filelocal_dir = os.getcwd()ph.sftp_put_file(file=file, local_dir=local_dir, remote_dir=remote_dir)# 下载文件file3.txtfile = 'file3.txt'remote_dir = '/root/test_log/' + filelocal_dir = os.getcwd()ph.sftp_get_file(file=file, local_dir=local_dir, remote_dir=remote_dir)if __name__ == '__main__':main()
13423234-0e3934319aa622f6.png

这篇关于python3 paramiko 远程执行 ssh 命令、上传文件、下载文件的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1092092

相关文章

Linux join命令的使用及说明

《Linuxjoin命令的使用及说明》`join`命令用于在Linux中按字段将两个文件进行连接,类似于SQL的JOIN,它需要两个文件按用于匹配的字段排序,并且第一个文件的换行符必须是LF,`jo... 目录一. 基本语法二. 数据准备三. 指定文件的连接key四.-a输出指定文件的所有行五.-o指定输出

Linux jq命令的使用解读

《Linuxjq命令的使用解读》jq是一个强大的命令行工具,用于处理JSON数据,它可以用来查看、过滤、修改、格式化JSON数据,通过使用各种选项和过滤器,可以实现复杂的JSON处理任务... 目录一. 简介二. 选项2.1.2.2-c2.3-r2.4-R三. 字段提取3.1 普通字段3.2 数组字段四.

Linux kill正在执行的后台任务 kill进程组使用详解

《Linuxkill正在执行的后台任务kill进程组使用详解》文章介绍了两个脚本的功能和区别,以及执行这些脚本时遇到的进程管理问题,通过查看进程树、使用`kill`命令和`lsof`命令,分析了子... 目录零. 用到的命令一. 待执行的脚本二. 执行含子进程的脚本,并kill2.1 进程查看2.2 遇到的

java中ssh2执行多条命令的四种方法

《java中ssh2执行多条命令的四种方法》本文主要介绍了java中ssh2执行多条命令的四种方法,包括分号分隔、管道分隔、EOF块、脚本调用,可确保环境配置生效,提升操作效率,具有一定的参考价值,感... 目录1 使用分号隔开2 使用管道符号隔开3 使用写EOF的方式4 使用脚本的方式大家平时有没有遇到自

mybatis直接执行完整sql及踩坑解决

《mybatis直接执行完整sql及踩坑解决》MyBatis可通过select标签执行动态SQL,DQL用ListLinkedHashMap接收结果,DML用int处理,注意防御SQL注入,优先使用#... 目录myBATiFBNZQs直接执行完整sql及踩坑select语句采用count、insert、u

java程序远程debug原理与配置全过程

《java程序远程debug原理与配置全过程》文章介绍了Java远程调试的JPDA体系,包含JVMTI监控JVM、JDWP传输调试命令、JDI提供调试接口,通过-Xdebug、-Xrunjdwp参数配... 目录背景组成模块间联系IBM对三个模块的详细介绍编程使用总结背景日常工作中,每个程序员都会遇到bu

Java服务实现开启Debug远程调试

《Java服务实现开启Debug远程调试》文章介绍如何通过JVM参数开启Java服务远程调试,便于在线上排查问题,在IDEA中配置客户端连接,实现无需频繁部署的调试,提升效率... 目录一、背景二、相关图示说明三、具体操作步骤1、服务端配置2、客户端配置总结一、背景日常项目中,通常我们的代码都是部署到远程

Linux命令rm如何删除名字以“-”开头的文件

《Linux命令rm如何删除名字以“-”开头的文件》Linux中,命令的解析机制非常灵活,它会根据命令的开头字符来判断是否需要执行命令选项,对于文件操作命令(如rm、ls等),系统默认会将命令开头的某... 目录先搞懂:为啥“-”开头的文件删不掉?两种超简单的删除方法(小白也能学会)方法1:用“--”分隔命

一个Java的main方法在JVM中的执行流程示例详解

《一个Java的main方法在JVM中的执行流程示例详解》main方法是Java程序的入口点,程序从这里开始执行,:本文主要介绍一个Java的main方法在JVM中执行流程的相关资料,文中通过代码... 目录第一阶段:加载 (Loading)第二阶段:链接 (Linking)第三阶段:初始化 (Initia

Python使用FastAPI实现大文件分片上传与断点续传功能

《Python使用FastAPI实现大文件分片上传与断点续传功能》大文件直传常遇到超时、网络抖动失败、失败后只能重传的问题,分片上传+断点续传可以把大文件拆成若干小块逐个上传,并在中断后从已完成分片继... 目录一、接口设计二、服务端实现(FastAPI)2.1 运行环境2.2 目录结构建议2.3 serv