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

作者:chier11 时间:2022-03-11 12:57:33 

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

来源:https://blog.51cto.com/chier11/2530085

标签:Python,telnetlib,模块
0
投稿

猜你喜欢

  • 最简便的备份MySQL数据库的方法

    2008-12-25 13:16:00
  • 简单了解Python读取大文件代码实例

    2022-10-23 11:46:19
  • Django中使用group_by的方法

    2023-04-13 21:26:34
  • MYSQL数据库教程:唯一编号

    2009-02-27 15:27:00
  • XMLHttpRequest的浏览器兼容代码写法

    2008-09-02 10:46:00
  • pandas删除指定行详解

    2021-09-21 10:08:37
  • Python用SSH连接到网络设备

    2022-01-20 08:57:41
  • python 实现目录复制的三种小结

    2023-09-01 12:17:20
  • Python对口红进行数据分析来选定情人节礼物

    2022-01-23 07:38:08
  • asp 页面允许CACHE的方法

    2011-02-16 11:20:00
  • 虚拟环境下搭建一个Django项目

    2023-06-15 12:30:39
  • 使用PHP 5.0创建图形的巧妙方法

    2023-10-27 00:59:07
  • PHP简单检测网址是否能够正常打开的方法

    2023-11-17 22:22:56
  • Python使用pyshp库读取shapefile信息的方法

    2023-07-27 04:56:36
  • Mootools 1.2教程(19)——Tooltips

    2008-12-25 13:26:00
  • Quester解读17条广告效果测定

    2007-11-27 12:51:00
  • Python实现端口检测的方法

    2022-02-01 21:21:02
  • python线程的几种创建方式详解

    2023-06-11 20:23:35
  • js用星投票的示例代码

    2007-12-29 13:11:00
  • 产品列表到底应该怎么做?

    2009-01-02 16:34:00
  • asp之家 网络编程 m.aspxhome.com