神剑山庄资源网 Design By www.hcban.com

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

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

标签:
Python3,telnetlib模块

神剑山庄资源网 Design By www.hcban.com
神剑山庄资源网 免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
神剑山庄资源网 Design By www.hcban.com

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

暂无如何在Python3中使用telnetlib模块连接网络设备的评论...

《魔兽世界》大逃杀!60人新游玩模式《强袭风暴》3月21日上线

暴雪近日发布了《魔兽世界》10.2.6 更新内容,新游玩模式《强袭风暴》即将于3月21 日在亚服上线,届时玩家将前往阿拉希高地展开一场 60 人大逃杀对战。

艾泽拉斯的冒险者已经征服了艾泽拉斯的大地及遥远的彼岸。他们在对抗世界上最致命的敌人时展现出过人的手腕,并且成功阻止终结宇宙等级的威胁。当他们在为即将于《魔兽世界》资料片《地心之战》中来袭的萨拉塔斯势力做战斗准备时,他们还需要在熟悉的阿拉希高地面对一个全新的敌人──那就是彼此。在《巨龙崛起》10.2.6 更新的《强袭风暴》中,玩家将会进入一个全新的海盗主题大逃杀式限时活动,其中包含极高的风险和史诗级的奖励。

《强袭风暴》不是普通的战场,作为一个独立于主游戏之外的活动,玩家可以用大逃杀的风格来体验《魔兽世界》,不分职业、不分装备(除了你在赛局中捡到的),光是技巧和战略的强弱之分就能决定出谁才是能坚持到最后的赢家。本次活动将会开放单人和双人模式,玩家在加入海盗主题的预赛大厅区域前,可以从强袭风暴角色画面新增好友。游玩游戏将可以累计名望轨迹,《巨龙崛起》和《魔兽世界:巫妖王之怒 经典版》的玩家都可以获得奖励。