如何在如何在Python3中使用中使用telnetlib模块连接网络设备模块连接网络设备
Python中专门提供了telnetlib库,用来完成基于telnet协议的通信功能。
python3下使用telnetlib模块连接网络设备经常会遇到字节与字符不匹配的问题
问题提示如下:
import telnetlib
Host = "10.10.10.10"
# 连接Telnet服务器
tn = telnetlib.Telnet(Host, port=23, timeout=10)
tn.set_debuglevel(0)
# 输入登录用户名
tn.read_until(b'login: ')
tn.write(b"admin" + b'')
# 输入登录密码
tn.read_until(b'Password: ')
tn.write(b"Admin@1234" + b'')
tn.read_until(b'#')
tn.write(b"cd /home/sd" + b'')
tn.read_until(b'#')
tn.write(b"ls -al" + b'')
r = tn.read_until(b'#').decode('ASCII')
r1 = r.split(r"")
for i in r1:
print(i)
tn.close()
以下是设备实例:
>>> tn=telnetlib.Telnet("10.10.0.6",timeout=2)
>>> tn.read_until(b'login: ',timeout=2)
b"******************************************************************
***** Copyright (c) 2004-2018 New H3C Technologies Co., Ltd. All rig
rved.** Without the owner's prior written consent,
** no decompiling or reverse-engineering shall be allowed.
***********************************************************
************\nlogin: "
>>> tn.write(b'admin'+b'')
>>> tn.read_until(b'Password: ',timeout=2)
b'jgtlPassword: '
>>> tn.write(b'Admin@123'+b'')
>>> tn.read_until(b'>')
b'<bangong-01>'
>>> tn.write(b'ping 10.10.0.7')
>>> tn.read_until(b'>')
以上是命令行执行的过程。写成脚本需要考虑两个问题,一个是变量的替换如何编码解封,一个是输出结果加解码
#-*- coding:utf-8 -*-
import telnetlib
import re
import csv
import sys
import time
from datetime import datetime
host_dict={
"ip":"10.10.0.6",
"user":"admin",
"pwd":"Admin@123"
}
def get_loss(addrlist):
host=host_dict["ip"] user=host_dict["user"] pwd=host_dict["pwd"] print (host)