如何在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))

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • Python3 pywin32模块安装的详细步骤

    python新手一枚,操作系统Win10 64 bit,Python版本,3.7 因为某个脚本需要用到win32con 和win32api模块,run --  cmd  ,使用easy_install pywin32 命令安装,提示错误,搜不到, 网上搜了下教程,分别用pip3 install pypiwin32  和python -m pip install pypiwin32 命令试了下,安装报错 (使用pip3 install pypiwin32 命令是下载pypiwin32-219.zi

  • Python3中configparser模块读写ini文件并解析配置的用法详解

    Python3中configparser模块简介 configparser 是 Pyhton 标准库中用来解析配置文件的模块,并且内置方法和字典非常接近.Python2.x 中名为 ConfigParser,3.x 已更名小写,并加入了一些新功能. 配置文件的格式如下: [DEFAULT] ServerAliveInterval = 45 Compression = yes CompressionLevel = 9 ForwardX11 = yes [bitbucket.org] User =

  • python3 动态模块导入与全局变量使用实例

    动态导入有两种: 1 __main__(): f="demo.A" aa=__main__(f) aa.A.t() 2 import importlib: import importlib f="demo.A" aa=importlib.import_module(f) aa.t() 全局变量使用: global_list.py: size=None A.py: from demo import global_list global_list.size=101 fr

  • Python3 shutil(高级文件操作模块)实例用法总结

    1.shutil是shell utility的缩写 shutil.move直接从一个地方挪到另一个地方,而os.rename常常只能重命名,不能挪动位置. 功能是: >>>shutil.move('old.txt',r'c:datarchive') >>>shutil.copy('old.txt',r'c:datarchive') >>>os.remove('junk.dat') 2.高级文件操作(拷贝/移动/压缩/解压缩) #!/usr/bin/en

  • python3光学字符识别模块tesserocr与pytesseract的使用详解

    OCR,即Optical Character Recognition,光学字符识别,是指通过扫描字符,然后通过其形状将其翻译成电子文本的过程,对应图形验证码来说,它们都是一些不规则的字符,这些字符是由字符稍加扭曲变换得到的内容,我们可以使用OCR技术来讲其转化为电子文本,然后将结果提取交给服务器,便可以达到自动识别验证码的过程 tesserocr与pytesseract是Python的一个OCR识别库,但其实是对tesseract做的一层Python API封装,pytesseract是Goog

  • 使用python telnetlib批量备份交换机配置的方法

    使用了telnetlib模块,首先登录到交换机,列出并获取配置文件的名称,然后通过tftp协议将配置文件传输到文件服务器上,为避免配置文件覆盖,将备份的配置文件名称统一加入日期以作区分. 1. 登录方式和口令有好几种,比较懒惰,通过不同列表以做区分,如果每个交换机口令都不相同的话,就需要额外处理了. 2. 交换机的配置文件也有多种类型,也是通过列表进行区分. 3. 有些交换机支持ftp和sftp,但测试发现有些虽然有相应的客户端命令,但传输总有问题.也不能将每个交换机都配置为ftp服务器,不安全

  • python3使用Pillow、tesseract-ocr与pytesseract模块的图片识别的方法

    1.安装Pillow pip install Pillow 2.安装tesseract-ocr github地址: https://github.com/tesseract-ocr/tesseract 或本地下载地址:https://www.jb51.net/softs/538925.html windows: The latest installer can be downloaded here: tesseract-ocr-setup-3.05.01.exe and tesseract-oc

  • 使用Python3 poplib模块删除服务器多天前的邮件实现代码

    背景: 因为工作需要,公司给每个员工都分配了一个邮箱 公司的各种业务都通过邮箱发送.虽然给每个员工的电脑都设置pop3登录但是他们的程序设定有保存服务器副本,所以大量邮件使得服务器存储占用巨大. 删除服务器上多天前的邮件 实现: 使用 Python poplib 进行删除查看操作 使用email.parser 进行内容解析 使用 dateutil.parser 做邮件日期转换 代码 # -*- coding: UTF-8 -*- import poplib import datetime imp

  • Python3 requests模块如何模仿浏览器及代理

    requests是使用Apache2 licensed 许可证的HTTP库. 用python编写. 比urllib2模块更简洁. Request支持HTTP连接保持和连接池,支持使用cookie保持会话,支持文件上传,支持自动响应内容的编码,支持国际化的URL和POST数据自动编码. 在python内置模块的基础上进行了高度的封装,从而使得python进行网络请求时,变得人性化,使用Requests可以轻而易举的完成浏览器可有的任何操作. 代码如下 import requests def xia

  • python3连接kafka模块pykafka生产者简单封装代码

    1.1安装模块 pip install pykafka 1.2基本使用 # -* coding:utf8 *- from pykafka import KafkaClient host = 'IP:9092, IP:9092, IP:9092' client = KafkaClient(hosts = host) # 生产者 topicdocu = client.topics['my-topic'] producer = topicdocu.get_producer() for i in ran

随机推荐