如何在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各种语言间时间的转化实现代码
Mar 23 Python
Python编程修改MP3文件名称的方法
Apr 19 Python
JS设计模式之责任链模式实例详解
Feb 03 Python
python后端接收前端回传的文件方法
Jan 02 Python
python实现QQ空间自动点赞功能
Apr 09 Python
python多进程下实现日志记录按时间分割
Jul 22 Python
python路径的写法及目录的获取方式
Dec 26 Python
以SQLite和PySqlite为例来学习Python DB API
Feb 05 Python
python opencv圆、椭圆与任意多边形的绘制实例详解
Feb 06 Python
使用Python爬取弹出窗口信息的实例
Mar 14 Python
python实现ssh及sftp功能(实例代码)
Mar 16 Python
浅谈python锁与死锁问题
Aug 14 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数据库类
2009/05/27 PHP
php中利用str_pad函数生成数字递增形式的产品编号
2013/09/30 PHP
PHP截取指定图片大小的方法
2014/12/10 PHP
PHP设计模式之简单投诉页面实例
2016/02/24 PHP
浅析php设计模式之数据对象映射模式
2016/03/03 PHP
W3C Group的JavaScript1.8 新特性介绍
2009/05/19 Javascript
有趣的javascript数组定义方法
2010/09/10 Javascript
javascript 学习笔记(onchange等)
2010/11/14 Javascript
解读JavaScript代码 var ie = !-[1,] 最短的IE判定代码
2011/05/28 Javascript
基于jquery ajax 用户无刷新登录方法详解
2012/04/28 Javascript
javascript数据类型示例分享
2015/01/19 Javascript
js获取页面description的方法
2015/05/21 Javascript
Javascript removeChild()删除节点及删除子节点的方法
2015/12/27 Javascript
Bootstrap导航条可点击和鼠标悬停显示下拉菜单
2016/11/25 Javascript
解决vue项目报错webpackJsonp is not defined问题
2018/03/14 Javascript
bootstrap 弹出框modal添加垂直方向滚轴效果
2018/07/09 Javascript
element-ui中Table表格省市区合并单元格的方法实现
2019/08/07 Javascript
简单文件操作python 修改文件指定行的方法
2013/05/15 Python
Python中模块与包有相同名字的处理方法
2017/05/05 Python
解决python 无法加载downsample模型的问题
2018/10/25 Python
python2与python3中关于对NaN类型数据的判断和转换方法
2018/10/30 Python
深入学习python多线程与GIL
2019/08/26 Python
利用rest framework搭建Django API过程解析
2019/08/31 Python
Pytorch 实现数据集自定义读取
2020/01/18 Python
Centos7下源码安装Python3 及shell 脚本自动安装Python3的教程
2020/03/07 Python
解决tensorflow 释放图,删除变量问题
2020/06/23 Python
基于opencv实现简单画板功能
2020/08/02 Python
python进行OpenCV实战之画图(直线、矩形、圆形)
2020/08/27 Python
马来西亚户外装备商店:PTT Outdoor
2019/07/13 全球购物
匡威俄罗斯官网:Converse俄罗斯
2020/05/09 全球购物
拾金不昧的表扬信
2014/01/16 职场文书
二手房购房意向书
2015/05/09 职场文书
pytorch 如何把图像数据集进行划分成train,test和val
2021/05/31 Python
MySQL的全局锁和表级锁的具体使用
2021/08/23 MySQL
Spring Security使用单点登录的权限功能
2022/04/03 Java/Android
python DataFrame中stack()方法、unstack()方法和pivot()方法浅析
2022/04/06 Python