1.首先安装 paramiko 第三方库:
pip install paramiko
出现如下图,表示安装成功:

2.编写 ssh工具类,我这里取名为 ssh_util.py
import paramiko
import socket
import time
class SshUtil:
def __init__(self, ip, username, password, port=22):
self.ip = ip
self.username = username
self.password = password
self.port = port
self.ssh = None
self.channel = None
self.sftp = None
def connect(self):
''''建立ssh远程连接'''
try:
self.ssh = paramiko.SSHClient()
self.ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.ssh.connect(hostname=self.ip, port=self.port, username=self.username, password=self.password)
self.channel = self.ssh.invoke_shell(width=240)
self.sftp = self.ssh.open_sftp()
print(f'成功连接远程主机:host = {self.ip}, user = {self.username}')
except Exception as e:
print(e)
def disconnect(self):
''''断开远程连接'''
if self.sftp:
self.sftp.close()
if self.channel:
self.channel.close()
if self.ssh:
self.ssh.close()
print('关闭远程连接')
def exec_command(self, cmd):
'''远程执行指令,非交互式,不维持会话状态'''
try:
stdin, stdout, stderr = self.ssh.exec_command()
output = stdout.read().decode().strip()
error = stderr.read().decode().strip()
return output, error
except Exception as e:
print(e)
def send(self, cmd, timeout=5):
'''交互式shell的写方法,可维持会话状态, 将执行指令写入管道,发送给远程主机'''
try:
cmd = f'{cmd}\n'.encode('utf-8')
self.channel.send(cmd)
except socket.timeout:
print('发送指令超时')
def read(self, timeout=5, keyword='$'):
'''交互式shell的读方法,读取管道中的响应数据,直到超时没有读取到关键字,则将之前读到的数据返回'''
startTime = time.time()
result = ''
while True:
if self.channel.recv_ready():
output = self.channel.recv(65535).decode('utf-8')
result += output
# 结果中查到了关键字,则退出循环
if keyword in result:
break
# 等待读取结果超时,则退出循环
nowTime = time.time()
if nowTime - startTime > timeout:
print('等待读取结果超时!')
break
time.sleep(0.1)
return result
def read_remote_file(self, remotePath):
'''读取远端文件内容'''
try:
with self.sftp.open(remotePath, 'r') as f:
data = f.read().decode('utf-8')
return data
except Exception as e:
print(e)
def rewrite_remote_file(self, remotePath, data):
'''重写远端文件内容'''
try:
with self.sftp.open(remotePath, 'w') as f:
f.write(data)
except Exception as e:
print(e)
if __name__ == '__main__':
# 主机信息
ip = '192.168.215.1'
username = 'admin'
password = '123456'
# 创建对象
ssh = SshUtil(ip, username, password)
ssh.connect()
# 非交互式命令
cmd = 'pwd'
output, error = ssh.exec_command(cmd)
print(output)
# 交互式命令(比如连接上以后,会显示一个菜单界面)
result = ssh.read(5, 'Menu') # 读取到主菜单页面显示完毕
print(result)
ssh.send('Q') # 退出主菜单
result = ssh.read()
print(result)
ssh.disconnect()
290

被折叠的 条评论
为什么被折叠?



