如何在Python3中使用telnetlib模块连接网络设备


Posted in Python onSeptember 21, 2020

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))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

Python 相关文章推荐
Python中使用MELIAE分析程序内存占用实例
Feb 18 Python
Python字典操作详细介绍及字典内建方法分享
Jan 04 Python
Python使用requests发送POST请求实例代码
Jan 25 Python
对PyQt5中树结构的实现方法详解
Jun 17 Python
Django使用消息提示简单的弹出个对话框实例
Nov 15 Python
pytorch 数据处理:定义自己的数据集合实例
Dec 31 Python
Python实现队列的方法示例小结【数组,链表】
Feb 22 Python
使用Python和百度语音识别生成视频字幕的实现
Apr 09 Python
Python通过文本和图片生成词云图
May 21 Python
Python使用urlretrieve实现直接远程下载图片的示例代码
Aug 17 Python
python drf各类组件的用法和作用
Jan 12 Python
Python Matplotlib绘制两个Y轴图像
Apr 13 Python
总结Pyinstaller的坑及终极解决方法(小结)
Sep 21 #Python
python生成xml时规定dtd实例方法
Sep 21 #Python
Python中的特殊方法以及应用详解
Sep 20 #Python
matplotlib 三维图表绘制方法简介
Sep 20 #Python
Python三维绘图之Matplotlib库的使用方法
Sep 20 #Python
scrapy利用selenium爬取豆瓣阅读的全步骤
Sep 20 #Python
Python操作dict时避免出现KeyError的几种解决方法
Sep 20 #Python
You might like
php接口与接口引用的深入解析
2013/08/09 PHP
php操作mysql数据库的基本类代码
2014/02/25 PHP
PHP实现无限分类的实现方法
2016/11/14 PHP
PHP+MYSQL实现读写分离简单实战
2017/03/13 PHP
Laravel 模型使用软删除-左连接查询-表起别名示例
2019/10/24 PHP
js ondocumentready onmouseover onclick onmouseout 样式
2010/07/22 Javascript
setTimeout函数兼容各主流浏览器运行执行效果实例
2013/06/13 Javascript
JavaScript中创建字典对象(dictionary)实例
2015/03/31 Javascript
JS实现自动固定顶部的悬浮菜单栏效果
2015/09/16 Javascript
JavaScript检查子字符串是否在字符串中的方法
2016/02/03 Javascript
AngularJS教程之环境设置
2016/08/16 Javascript
详解nodejs微信公众号开发——3.封装消息响应模块
2017/04/10 NodeJs
关于laydate.js加载laydate.css路径错误问题解决
2017/12/27 Javascript
vue实现路由懒加载及组件懒加载的方式
2019/06/11 Javascript
JavaScript:ES2019 的新特性(译)
2019/08/08 Javascript
vue中通过使用$attrs实现组件之间的数据传递功能
2019/09/01 Javascript
[00:03]DOTA2新版本PA至宝展示
2014/11/19 DOTA
[57:53]DOTA2上海特级锦标赛主赛事日 - 2 败者组第二轮#3OG VS VP
2016/03/03 DOTA
Python排序搜索基本算法之插入排序实例分析
2017/12/11 Python
Python装饰器用法示例小结
2018/02/11 Python
django 开发忘记密码通过邮箱找回功能示例
2018/04/17 Python
python numpy 一维数组转变为多维数组的实例
2018/07/02 Python
python opencv实现旋转矩形框裁减功能
2018/07/25 Python
使用python实现语音文件的特征提取方法
2019/01/09 Python
对python3 Serial 串口助手的接收读取数据方法详解
2019/06/12 Python
python Opencv计算图像相似度过程解析
2019/12/03 Python
python安装后的目录在哪里
2020/06/21 Python
Numpy中的数组搜索中np.where方法详细介绍
2021/01/08 Python
CSS3关于z-index不生效问题的解决
2020/02/19 HTML / CSS
DHC中国官方购物网站:日本通信销售No.1化妆品
2016/08/20 全球购物
Otticanet美国:最顶尖的世界名牌眼镜, 能得到打折季的价格
2019/03/10 全球购物
印度排名第一的蛋糕、鲜花和礼品送货:Winni
2019/08/02 全球购物
青年创业培训欢迎词
2014/01/10 职场文书
推荐信模板
2014/05/09 职场文书
技术岗位竞聘演讲稿
2014/05/16 职场文书
2015年安全保卫工作总结
2015/05/14 职场文书