1. 程式人生 > 程式設計 >如何在Python3中使用telnetlib模組連線網路裝置

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

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。