用Python怎么telnet到網絡設備


0.前言

Telnet協議屬於TCP/IP協議族里的一種,對於我們這些網絡攻城獅來說,再熟悉不過了,常用於遠程登陸到網絡設備進行操作,但是,它的缺陷太明顯了,就是不安全,信息明文傳送,極容易被攻擊竊取信息,不推薦使用,但本節我還是先從它入手哈。

1. 測試環境及關鍵代碼解釋

1.1 簡單測試環境

  1. 使用python3環境
  2. 使用內置telnetlib模塊
  3. 簡單的實驗環境
    在這里插入圖片描述
    在這里插入圖片描述
說明:
cmd.txt文件里面命令如下:
  terminal length 0
  show clock
  show ip interface brief
list.txt文件里面的IP如下:
  192.168.1.101
  192.168.1.102
  192.168.1.103

1.2 關鍵代碼

import xx:導入模塊
class xx:定義類
def xx: 定義函數
try-except :處理可能引發的異常
tn.read_until(expected, timeout=None):等待預期字符串或等待超時
tn.write(buffer):寫入的字符串(意思發送給命令給設備)
tn.expect(list, timeout=None):讀顯,list采用正則表達式(意思把執行過程顯示出來)
tn.read_very_eager():讀顯(意思把執行過程顯示出來)
tn.open(host, port=0[, timeout]):連接主機
tn.close():關閉連接

Tips:終端與網絡設備交付的信息是以byte類型,所以要把終端上的字符串encode編碼轉換為byte對象,網絡設備回顯的byte信息要decode解碼。

2. 完整代碼

'''
歡迎關注微信公眾號:'diandijishu'
  此平台是網路工程師個人日常技術、項目案例經驗分享,
  為鞏固及提升技術能力乃至共享所學所知技術
  也歡迎各位工程師一起分享、一起成長。
'''

#!/usr/bin/env python
#coding:utf-8

'導入模塊'
from telnetlib import Telnet
import time
import logging

'定義類'
class TelnetClient():
    '初始化屬性'
    def __init__(self):
        self.tn = Telnet()
    '定義login_host函數,用於登陸設備'
    def login_host(self,ip,username,password,enable=None,verbose=True):
        '連接設備,try-except結構'
        try:
            self.tn.open(ip,port=23)
        except:
            logging.warning('%s網絡連接失敗' %ip)
            return False
        '輸入用戶名'
        self.tn.read_until(b'Username:', timeout=1)
        self.tn.write(b'\n')
        self.tn.write(username.encode()   b'\n')
        rely = self.tn.expect([], timeout=1)[2].decode().strip()    #讀顯
        if verbose:
            print(rely)
        '輸入用戶密碼'
        self.tn.read_until(b'Password:', timeout=1)
        self.tn.write(password.encode()   b'\n')
        rely = self.tn.expect([], timeout=1)[2].decode().strip()
        if verbose:
            print(rely)
        '進去特權模式'
        if enable is not None:
            self.tn.write(b'enable\n')
            self.tn.write(enable.encode()   b'\n')
            if verbose:
                rely = self.tn.expect([], timeout=1)[2].decode().strip()
                print(rely)
                time.sleep(1)

        rely = self.tn.read_very_eager().decode()
        if 'Login invalid' not in rely:
            logging.warning('%s登陸成功' % ip)
            return True
        else:
            logging.warning('%s登陸失敗,用戶名或密碼錯誤' % ip)
            return False

    '定義do_cmd函數,用於執行命令'
    def do_cmd(self,cmds):
        '讀取文件,for語句循環執行命令'
        with open(cmds) as cmd_obj:
            for cmd in cmd_obj:
                self.tn.write(cmd.encode().strip()   b'\n')
                time.sleep(2)
                rely = self.tn.read_very_eager().decode()
                logging.warning('命令執行結果:\n %s' %rely)
    '定義logout_host函數,關閉程序'
    def logout_host(self):
        self.tn.close()

if __name__ == '__main__':
    username = 'cisco'  #用戶名
    password = 'cisco' #密碼
    enable = 'cisco'    #特權密碼
    lists = 'list.txt'  #存放IP地址文件,相對路徑
    cmds = 'cmd.txt'    #存放執行命令文件,相對路徑
    telnet_client = TelnetClient()
    '讀取文件,for語句循環登陸IP'
    with open(lists,'rt') as list_obj:
        for ip in list_obj:
            '如果登錄結果為True,則執行命令,然后退出'
            if telnet_client.login_host(ip.strip(),username,password,enable):
                telnet_client.do_cmd(cmds)
                telnet_client.logout_host()
                time.sleep(2)

3. 運行效果

在這里插入圖片描述

備注:這個運行的效果我只存放了192.168.1.101這個IP,精簡一下,為了效果。

4. 報錯效果

4.1 遠程連接不上

在這里插入圖片描述

4.2 用戶名和密碼錯誤

在這里插入圖片描述

5. 碎碎語

這些只是一些簡單的代碼,待優化的地方還是很多,先給小伙伴們學習一下,telnet協議是個不安全的,基本網絡環境很少用了,ssh為常用的協議,安全又好用,下個文章我給大家介紹python如何使用ssh模塊哈。
本人代碼功夫不深,如有缺陷望指教,多謝。


如果喜歡我的文章,歡迎關注我的公眾號:點滴技術,掃碼關注,不定期分享

點滴技術


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM