文章目录
- 介绍
- 实例
- 登录设备执行命令
- 在代码中解决分页问题,并保存日志
- 常见问题
- 处理分页问题
介绍
- 官网资料
实例
登录设备执行命令
- 代码
from telnetlib import Telnet ######################################## 设置变量 ######################################## host = '192.168.85.202' port = 23 username = 'admin' password = 'admin' ######################################## 设置变量 ######################################## tn = Telnet(host=host,port=port,timeout=5) # 如果定义了变量username,则输入用户名 if "username" in vars(): # 读取回显,判断出现"Username:"字符 tn.read_until(b'Username:',timeout=1) # 发送用户名和回编码为字节 tn.write(username.encode("utf-8") + b'\n') # 读取回显,判断出现字符"Password:" tn.read_until(b'Password:') # 发送密码和回车 tn.write(password.encode("utf-8") + b'\n') # 发送命令 tn.read_until(b'>',timeout=5) # 开始发送命令,编码成字节格式 tn.write(b'display version' + b'\n') output = tn.read_until(b'>',timeout=5) print(output.decode("utf-8"))
在代码中解决分页问题,并保存日志
- 有的设备不支持类似’screen-length 0 temporary’的命令,需要使用代码解决分页的问题
- 代码
from pathlib import Path from telnetlib import Telnet from datetime import datetime ######################################## 设置变量 ######################################## host = '10.10.10.10' port = 23 #username = 'admin' password = 'admin' # 等待提示符出来,判断命令执行结束,推荐改成自己的设备名称 prompt = '<HuaWei>' log_file = Path(f'/opt/bdidc/share/share/work/OA/devices/YD-IDC-SJZX-OA1/{datetime.now().strftime("%Y-%m-%d")}.txt') ######################################## 设置变量 ######################################## tn = Telnet(host=host,port=port,timeout=5) if "username" in vars(): # 读取回显,判断出现"Username:"字符 tn.read_until(b'Username:',timeout=1) # 发送用户名和回编码为字节 tn.write(username.encode("utf-8") + b'\n') # 读取回显,判断出现字符"Password:" tn.read_until(b'Password:') # 发送密码和回车,需编码为字节 tn.write(password.encode("utf-8") + b'\n') logined = tn.read_until(prompt.encode("utf-8"),timeout=5) if prompt.encode("utf-8") not in logined: print('未成功登录设备,程序结束') else: print('成功登录设备,开始执行命令') # 开始发送命令,编码成字节格式 tn.write(b'display current-configuration' + b'\n') # 处理分页 output = str() while True: # 读取输出直到看到"More"提示 output_temp = tn.read_until(b"More", timeout=5) output += output_temp.decode('utf-8') #print(output_temp.decode('utf-8'), end='') # 输出当前页的内容 if b"More" in output_temp: tn.write(b" ") # 模拟按下空格键来继续显示下一页内容 else: break # 如果没有"More"提示了,退出循环 output += tn.read_until(prompt.encode("utf-8"),timeout=5).decode("utf-8") tn.close() # 保存日志到文件 output2 = output.strip() output2 = output2.split('\n') file = open(log_file,'w') for line in output2: if "More" in line: line = line.replace(' ---- More ----[6n[16D [16D','') file.write(line.replace('\r','') + '\n') file.close() print('脚本运行结束')
常见问题
处理分页问题
- 有的设备不支持类似’screen-length 0 temporary’的命令,需要使用代码解决分页的问题
- 代码
# 处理分页 while True: # 读取输出直到看到"More"提示 output = tn.read_until(b"More", timeout=5) print(output.decode('utf-8'), end='') # 输出当前页的内容 if b"More" in output: tn.write(b" ") # 模拟按下空格键来继续显示下一页内容 else: break # 如果没有"More"提示了,退出循环