如何在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 win系统下 打开TXT文件的实例

    在python win系统下 打开TXT文件的实例

    下面小编就为大家分享一篇在python win系统下 打开TXT文件的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-04-04
  • Python concurrent.futures模块使用实例

    Python concurrent.futures模块使用实例

    这篇文章主要介绍了Python concurrent.futures模块使用实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-12-12
  • Python爬虫获取基金列表

    Python爬虫获取基金列表

    这篇文章主要介绍了Python爬虫获取基金列表,python爬虫用来收集数据是最直接和常用的方法,可以使用python爬虫程序获得大量的数据,下文更多相关内容介绍,需要的小伙伴可以参考一下
    2022-05-05
  • 用Python获取智慧校园每日课表并自动发送至邮箱

    用Python获取智慧校园每日课表并自动发送至邮箱

    很多小伙伴们都在为查看智慧校园课表而烦恼,今天特地整理了这篇文章,不仅可以用Python获取智慧校园每日课表,还会自动发至你邮箱,需要的朋友可以参考下
    2021-05-05
  • Python subprocess模块功能与常见用法实例详解

    Python subprocess模块功能与常见用法实例详解

    这篇文章主要介绍了Python subprocess模块功能与常见用法,结合实例形式详细分析了subprocess模块功能、常用函数相关使用技巧,需要的朋友可以参考下
    2018-06-06
  • Python+Plotly绘制精美的数据分析图

    Python+Plotly绘制精美的数据分析图

    Plotly 是目前已知的Python最强绘图库,比Echarts还强大许多。它的绘制通过生成一个web页面完成,并且支持调整图像大小,动态调节参数。本文将利用Plotly绘制精美的数据分析图,感兴趣的可以了解一下
    2022-05-05
  • 详解使用python的logging模块在stdout输出的两种方法

    详解使用python的logging模块在stdout输出的两种方法

    这篇文章主要介绍了详解使用python的logging模块在stdout输出的相关资料,需要的朋友可以参考下
    2017-05-05
  • Python实现Excel和CSV之间的相互转换

    Python实现Excel和CSV之间的相互转换

    通过使用Python编程语言,编写脚本来自动化Excel和CSV之间的转换过程,可以批量处理大量文件,定期更新数据,并集成转换过程到自动化工作流程中,本文将介绍如何使用Python 实现Excel和CSV之间的相互转换,需要的朋友可以参考下
    2024-03-03
  • 详解Python3中的迭代器和生成器及其区别

    详解Python3中的迭代器和生成器及其区别

    本篇将介绍Python3中的迭代器与生成器,描述可迭代与迭代器关系,并实现自定义类的迭代器模式。非常具有实用价值,需要的朋友可以参考下
    2018-10-10
  • 使用jupyter notebook运行python和R的步骤

    使用jupyter notebook运行python和R的步骤

    这篇文章主要介绍了使用jupyter notebook运行python和R的步骤,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-08-08

最新评论