福田建设网站,中国舆情在线网,江西商城网站建设,技术支持 上海做网站前言
Python的Paramiko库#xff0c;它是一个用于实现SSHv2协议的客户端和服务器的库。通过使用Paramiko#xff0c;我们可以在Python程序中轻松地实现远程服务器的管理、文件传输等功能。特别做智能硬件产品的同学要熟悉它#xff0c;因为它能为你减少很多麻烦#xff0c…前言
Python的Paramiko库它是一个用于实现SSHv2协议的客户端和服务器的库。通过使用Paramiko我们可以在Python程序中轻松地实现远程服务器的管理、文件传输等功能。特别做智能硬件产品的同学要熟悉它因为它能为你减少很多麻烦在我以前的工作中对智能硬件做各种测试就是通过Paramiko连接设备下发各种命令
一.安装
pip install paramiko
二.基本用法 1.创建一个ssh连接客户端
import paramiko
ssh paramiko.SSHClient()ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
2.添加服务器的SSH密钥可选
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) 2.connect()创建连接连接远程服务各种智能硬件服务器等
hostname 192.168.31.230port 22username kalipassword kalissh.connect(hostname, port, username, password) 3.执行远程命令
stdin, stdout, stderr ssh.exec_command(ls)print(stdout.read().decode()) # 打印输出结果print(stderrh.read().decode())# 输出错误信息# 返回结果 DesktopDocumentsDownloadsMusicPicturesPublicTemplatesVideos
4.文件下载
local_file D:/code/ssh/local_file.txt # 本地文件路径和名称remote_file /home/kali/remote_file.txt # 远程文件路径和名称sftp ssh.open_sftp() # 打开SFTP会话sftp.get(remote_file, local_file) # 从远程服务器下载文件到本地sftp.close() # 关闭SFTP会话 5.文件上传
local_file D:/code/ssh/local_file2.txt # 本地文件路径和名称remote_file /home/kali/remote_file2.txt # 远程文件路径和名称sftp ssh.open_sftp() # 打开SFTP会话sftp.put(local_file, remote_file) # 上传本地文件到远程服务器sftp.close() # 关闭SFTP会话 6.关闭连接
ssh.close() #关闭连接
三.完整代码如下
import paramikossh paramiko.SSHClient() # 创建客服端ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # 添加秘钥hostname 192.168.31.230port 22username kalipassword kalissh.connect(hostname, port, username, password) # 创建连接stdin, stdout, stderr ssh.exec_command(ls) # 执行lsprint(stdout.read().decode())# 下载local_file D:/code/ssh/local_file.txt # 本地文件路径和名称remote_file /home/kali/remote_file.txt # 远程文件路径和名称sftp ssh.open_sftp() # 打开SFTP会话sftp.get(remote_file, local_file) # 从远程服务器下载文件到本地# 上传local_file2 D:/code/ssh/local_file2.txt # 本地文件路径和名称remote_file2 /home/kali/remote_file2.txt # 远程文件路径和名称sftp ssh.open_sftp() # 打开SFTP会话sftp.put(local_file2, remote_file2) # 上传本地文件到远程服务器sftp.close() # 关闭SFTP会话ssh.close() # 关闭连接