Python~paramiko库使用

Python~paramiko库使用,第1张

Python环境:3.9

paramiko包含了两个核心组件:SSHClientSFTPClient

  • SSHClient 类:SSHClient 类是与SSH服务器会话的高级表示。该类集成了Transport,Channel 和SFTPClient 类。
  • SFTClient 类:该类通过一个打开的SSH Transport 会话创建SFTP会话通道并执行远程文件 *** 作。
目的

巡检设备,并将收集到的信息保存为文本。

拓扑

注:这里使用EVE模拟器,设备为华为CE12800交换机,通过桥接,电脑能正常远程到华为CE12800

思路
  1. 通过paramiko实例连接到交换机
  2. 将巡检的命令写入到文本。
  3. 读取文件后,遍历循环这些命令。
  4. 收集回显信息,保存为文本。
交换机配置
system-view immediately
aaa
 undo local-user policy security-enhance
 local-user huawei password irreversible-cipher password
 local-user huawei service-type ssh
 local-user huawei level 3
quit

stelnet server enable
ssh user huawei
ssh user huawei authentication-type password
ssh user huawei service-type all
ssh authorization-type default aaa

user-interface vty 0 4
 authentication-mode aaa
quit

interface MEth0/0/0
 undo shutdown
 ip address 192.168.179.200 255.255.255.0
quit
完整代码
import paramiko
import time

ip = "192.168.179.200"
port = 22
username = "huawei"
password = "password"

# 创建 SSHClient 实例
ssh_proc = paramiko.SSHClient()

# 自动添加主机名及主机密钥到本地HostKeys对象
# 如果不添加,那么不再本地know_hosts文件中记录的主机将无法连接
ssh_proc.set_missing_host_key_policy(paramiko.AutoAddPolicy())

# 连接交换机
ssh_proc.connect(hostname=ip, port=port, username=username, password=password)

# 创建一个交互 shell 会话
shell = ssh_proc.invoke_shell()

# 读取 huawei.txt 文件,这里是一些需要指定的命令
with open('huawei.txt',mode='r') as f:
	# 读取文本内容,转换成列表,用于后面for 循环执行命令
    commands = list(f)
    # 列表推导式,删除文本中的空值
    commands = [x.strip('') for x in commands if x.strip() != '']

# 遍历循环列表
for i in commands:
    shell.send(i)
    time.sleep(0.5)
    
# 接受回显信息
data = shell.recv(999999).decode()

# 将接收的回显信息保存为“日期_logs.log”文件
with open(f'{time.strftime("%Y%m%d")}_logs.log',mode='w',encoding="utf-8") as f:
    f.write(data)
    
print("收集完成!")
ssh_proc.close()

脚本执行完成后,当前路径下会生成一个20220421-logs.log文件。文件名会根据日期变动。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/728940.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-26
下一篇 2022-04-26

发表评论

登录后才能评论

评论列表(0条)

保存