用Python怎麼telnet到網絡設備

0.前言

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

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.readveryeager():讀顯(意思把執行過程顯示出來)tn.open(host, port=0[, timeout]):鏈接主機tn.close():關閉鏈接git

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

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模塊哈。本人代碼功夫不深,若有缺陷望指教,多謝。安全

若是喜歡的個人文章,歡迎關注個人公衆號:點滴技術,掃碼關注,不按期分享微信

點滴技術

相關文章
相關標籤/搜索