如何在Python3中使用telnetlib模块连接网络设备
作者:chier11 发布时间:2022-03-11 12:57:33
标签:Python,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'\n')
# 输入登录密码
tn.read_until(b'Password: ')
tn.write(b"Admin@1234" + b'\n')
tn.read_until(b'#')
tn.write(b"cd /home/sd" + b'\n')
tn.read_until(b'#')
tn.write(b"ls -al" + b'\n')
r = tn.read_until(b'#').decode('ASCII')
r1 = r.split(r"\r\n")
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"\r\n******************************************************************
****\r\n* Copyright (c) 2004-2018 New H3C Technologies Co., Ltd. All rig
rved.*\r\n* Without the owner's prior written consent,
*\r\n* no decompiling or reverse-engineering shall be allowed.
*\r\n**********************************************************
************\r\n\r\nlogin: "
>>> tn.write(b'admin'+b'\n')
>>> tn.read_until(b'Password: ',timeout=2)
b'jgtl\r\r\nPassword: '
>>> tn.write(b'Admin@123'+b'\n')
>>> tn.read_until(b'>')
b'\r\n<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)
resultlist = []
#try:
tn = telnetlib.Telnet(host, timeout=2)
print ("AA")
if len(host_dict["pwd"]) and len(host_dict["user"]):
print ("BB")
tn.read_until(b"login: ", timeout=3)
#tn.write(b"admin"+b"\n")
tn.write(user.encode()+b"\n")
tn.read_until(b"Password: ", timeout=3)
#tn.write(b"Admin@123"+b"\n")
tn.write(pwd.encode()+ b"\n")
# p_error = re.compile("found at")
if tn.read_until(b">", timeout=4).find(b">") != -1:
print("Connect to {host} ...... ".format(host=host))
tn.write(b"ping 127.0.0.1\n")
print (tn.read_until(b'01>'))
else:
print("%s Wrong username or password!!!" % host)
return ""
#tn.read_until(b">")
if len(addrlist) != 0:
for i in range(len(addrlist)-1):
tep = {}
command = "ping " + addrlist[i]
print("command:", command)
tn.write(command.encode() + b"\n")
result = str(tn.read_until(b"01>"))
print(result)
re_loss = re.compile("\d+\.\d+%")
loss = re_loss.findall(result)
tep[host] = loss[0]
resultlist.append(tep)
#if p_error.search(result.decode()):
# print("There is a error in this command: {0}".format(c.decode()))
tn.close()
#except Exception as e:
#if e:
# print ("Connect to {host} Failed!!!".format(host=host),e)
#return ""
return resultlist
if __name__=="__main__":
addrlist=['10.10.0.2','10.10.0.5']
print ("get_loss",get_loss(addrlist))
来源:https://blog.51cto.com/chier11/2530085
0
投稿
猜你喜欢
- 先来看看基本的定义:channel是Go语言中的一个核心类型,可以把它看成管道。并发核心单元通过它就可以发送或者接收数据进行通讯,这在一定程
- 本文实例讲述了Python实现合并同一个文件夹下所有txt文件的方法。分享给大家供大家参考,具体如下:一、需求分析合并一个文件夹下所有txt
- python最值与下标最大值的下标winner = np.argmax(scores)多个最大值的下标(np.argwhere返回数组中非0
- css实现的圆角矩形的方式很多,但要追求灵活型,上面的结构简单,看起来爽一点注意css所用的图片路径,已修改兼容ie6 ie7 ff ,IE
- 最近 全栈数据工程师养成攻略 的微信群已经将近500人,开了二群之后为了打通不同微信群之间的消息,花了点时间做了个消息同步机器人,在任意群收
- IE6绝对定位的bug及其解决办法。position:absolute定位在IE6下存在left和bottom的定位错误问题:<!–I
- 在 JavaScript 中,可以用 instanceof 来判断一个对象是不是某个类或其子类的实例。比如:// 代码
- 本文实例讲述了python简单实现基数排序算法。分享给大家供大家参考。具体实现方法如下:from random import randint
- 在Microsoft SQL Server 2000中,用于数据存储的实用工具是数据库。数据库的物理表现是操作系统文件,即在物理上,一个数据
- 本文中介绍的主要是SQL语句,请大家不要在Access中使用。SQL的分类:DDL—数据定义语言(CREATE,ALTE
- Excel 中的每一个单元,都会有这些属性:颜色(colors)、number formatting、字体(fonts)、边界(border
- 使用图层可以像素为单位精确定位页面元素,并且可以将层放置在页面的任意位置。当把页面元素放入图层之中时,还可以控制哪个显示在前面、哪个显示在后
- 几个常用的js小函数,在表单验证时也许您用得到:一检查是否是email地址,二检查是否为数字,三检查是否为电话号码,四检查num是否是负数或
- 而Easp类中提供了大量实用的ASP通用过程及方法,可以简化大部分的ASP操作。目前只提供了VBScript版,JScript版将来可能会提
- 本文实例讲述了python根据出生日期返回年龄的方法。分享给大家供大家参考。具体实现方法如下:def CalculateAge(self,
- 本文介绍了详解TensorFlow在windows上安装与简单示例,分享给大家,具体如下:安装说明平台:目前可在Ubuntu、Mac OS、
- Q:Dreamweaver(简称DW)中如何输入空格?A:按下“Ctrl+Shift+空格键”或者在中
- 李开复曾经在年前表示,谷歌公司会在今年春节期间,对Google谷歌的搜索结果页进行“从未有过的尝试”修改,以凸显农历春节的喜庆气氛。现在,输
- 本文实例讲述了Python2与Python3的区别。分享给大家供大家参考,具体如下:python2与python3的区别1、性能2、编码格式
- 原文链接:https://vien.tech/article/157前言本文将介绍ubuntu系统下如何定时执行shell脚本、python