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

 更新时间:2020年09月21日 08:35:40   作者:chier11  
这篇文章主要介绍了如何在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'\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中垃圾回收和del语句详解

    Python中垃圾回收和del语句详解

    Python语言默认采用的垃圾收集机制是引用计数法,本文详细的介绍了Python中垃圾回收和del语句详解,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2018-11-11
  • Python第三方库xlrd/xlwt的安装与读写Excel表格

    Python第三方库xlrd/xlwt的安装与读写Excel表格

    最近开始学习python,想做做简单的自动化测试,需要读写excel,于是就接触到了Python的第三方库xlrd和xlwt,下面这篇文章就给大家主要介绍了Python中第三方库xlrd/xlwt的安装与读写Excel表格的方法,需要的朋友可以参考借鉴。
    2017-01-01
  • python实现诗歌游戏(类继承)

    python实现诗歌游戏(类继承)

    这篇文章主要为大家详细介绍了python实现诗歌游戏,根据上句猜下句、猜作者、猜朝代、猜诗名,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-02-02
  • 深入了解PyQt5中的图形视图框架

    深入了解PyQt5中的图形视图框架

    PyQt5中图形视图框架主要包含三个类:QGraphicsItem图元类、QGraphicsScene场景类和QGraphicsView视图类。本文将通过示例详细讲解一下这三个类,感兴趣的可以学习一下
    2022-03-03
  • python套接字流重定向实例汇总

    python套接字流重定向实例汇总

    套接字是一种具有之前所说的“通信端点”概念的计算网络数据结构。相当于电话插口,没它无法通信,这个比喻非常形象。今天我们就来汇总一下套接字流重定向的实例
    2016-03-03
  • python实现两张图片的像素融合

    python实现两张图片的像素融合

    这篇文章主要为大家详细介绍了python实现两张图片的像素融合,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-02-02
  • Python 获取新浪微博的最新公共微博实例分享

    Python 获取新浪微博的最新公共微博实例分享

    因为工作,需要抓取微博内容。在百度上找到多篇关于用Python实现抓取新浪微博的文章,但似乎都不凑效,还是自己来吧,俗话说自己动手丰衣足食嘛
    2014-07-07
  • Flask web开发处理POST请求实现(登录案例)

    Flask web开发处理POST请求实现(登录案例)

    这篇文章主要介绍了Flask web开发处理POST请求实现(登录案例),小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
    2018-07-07
  • 全面了解Nginx, WSGI, Flask之间的关系

    全面了解Nginx, WSGI, Flask之间的关系

    下面小编就为大家分享一篇全面了解Nginx, WSGI, Flask之间的关系,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-01-01
  • python树莓派红外反射传感器

    python树莓派红外反射传感器

    这篇文章主要为大家详细介绍了python树莓派红外反射传感器,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2019-01-01

最新评论