如何在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 相关文章推荐
详解C++编程中一元运算符的重载
Jan 19 Python
python监控linux内存并写入mongodb(推荐)
Sep 11 Python
python 创建一个空dataframe 然后添加行数据的实例
Jun 07 Python
linux查找当前python解释器的位置方法
Feb 20 Python
python基础梳理(一)(推荐)
Apr 06 Python
Python 安装第三方库 pip install 安装慢安装不上的解决办法
Jun 18 Python
简单了解python高阶函数map/reduce
Jun 28 Python
Python3显示当前时间、计算时间差及时间加减法示例代码
Sep 07 Python
python爬虫添加请求头代码实例
Dec 28 Python
对tensorflow中cifar-10文档的Read操作详解
Feb 10 Python
python GUI库图形界面开发之PyQt5信号与槽多窗口数据传递详细使用方法与实例
Mar 08 Python
pytorch中Schedule与warmup_steps的用法说明
May 24 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加Nginx实现动态裁剪图片方案
2014/03/10 PHP
Jquery ajaxsubmit上传图片实现代码
2010/11/04 Javascript
使用Js让Html中特殊字符不被转义
2013/11/05 Javascript
JS阻止冒泡事件以及默认事件发生的简单方法
2014/01/17 Javascript
调用jQuery滑出效果时闪烁的解决方法
2014/03/27 Javascript
jQuery中DOM树操作之使用反向插入方法实例分析
2015/01/23 Javascript
js图片轮播特效代码分享
2015/09/07 Javascript
JS+CSS实现简单滑动门(滑动菜单)效果
2015/09/19 Javascript
基于Jquery和CSS3制作数字时钟附源码下载(CSS3篇)
2015/11/24 Javascript
全面解析Bootstrap中nav、collapse的使用方法
2016/05/22 Javascript
Web 开发中Ajax的Session 超时处理方法
2017/01/19 Javascript
js中document.referrer实现移动端返回上一页
2017/02/22 Javascript
深入浅析AngularJS中的一次性数据绑定 (bindonce)
2017/05/11 Javascript
原生JS实现N级菜单的代码
2017/05/21 Javascript
详解JavaScript事件循环机制
2018/09/07 Javascript
在vue中实现点击选择框阻止弹出层消失的方法
2018/09/15 Javascript
vuex管理状态 刷新页面保持不被清空的解决方案
2019/11/11 Javascript
[00:23]DOTA2群星共贺开放测试 25日无码时代来袭
2013/09/23 DOTA
Python实现的爬虫功能代码
2017/06/24 Python
Python对列表去重的多种方法(四种方法)
2017/12/05 Python
详解Django中CBV(Class Base Views)模型源码分析
2019/02/25 Python
如何利用Python模拟GitHub登录详解
2019/07/15 Python
django的模型类管理器——数据库操作的封装详解
2020/04/01 Python
pytorch SENet实现案例
2020/06/24 Python
Python打印不合法的文件名
2020/07/31 Python
CSS3盒子模型详解
2013/04/24 HTML / CSS
巴西婴儿用品商店:Bebe Store
2017/11/23 全球购物
斯洛伐克香水和化妆品购物网站:Parfemy-Elnino.sk
2020/01/28 全球购物
质检员的岗位职责
2013/11/15 职场文书
优秀经理事迹材料
2014/02/01 职场文书
体育教师求职信
2014/06/30 职场文书
竞选纪律委员演讲稿
2014/09/13 职场文书
土木工程专业本科生求职信
2014/10/01 职场文书
深入开展党的群众路线教育实践活动心得体会
2014/11/05 职场文书
财务总监岗位职责
2015/02/03 职场文书
java实现面板之间切换功能
2022/06/10 Java/Android