用Python怎么telnet到網(wǎng)絡(luò)設(shè)備

0.前言

Telnet協(xié)議屬于TCP/IP協(xié)議族里的一種,對(duì)于我們這些網(wǎng)絡(luò)攻城獅來(lái)說(shuō),再熟悉不過(guò)了,常用于遠(yuǎn)程登陸到網(wǎng)絡(luò)設(shè)備進(jìn)行操作,但是,它的缺陷太明顯了,就是不安全,信息明文傳送,極容易被攻擊竊取信息,不推薦使用,但本節(jié)我還是先從它入手哈。

1. 測(cè)試環(huán)境及關(guān)鍵代碼解釋

1.1 簡(jiǎn)單測(cè)試環(huán)境

  1. 使用python3環(huán)境
  2. 使用內(nèi)置telnetlib模塊
  3. 簡(jiǎn)單的實(shí)驗(yàn)環(huán)境
說(shuō)明:
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 關(guān)鍵代碼

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

Tips:終端與網(wǎng)絡(luò)設(shè)備交付的信息是以byte類(lèi)型,所以要把終端上的字符串encode編碼轉(zhuǎn)換為byte對(duì)象,網(wǎng)絡(luò)設(shè)備回顯的byte信息要decode解碼。

2. 完整代碼

'''
歡迎關(guān)注微信公眾號(hào):'diandijishu'
  此平臺(tái)是網(wǎng)路工程師個(gè)人日常技術(shù)、項(xiàng)目案例經(jīng)驗(yàn)分享,
  為鞏固及提升技術(shù)能力乃至共享所學(xué)所知技術(shù)
  也歡迎各位工程師一起分享、一起成長(zhǎng)。
'''

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

'導(dǎo)入模塊'
from telnetlib import Telnet
import time
import logging

'定義類(lèi)'
class TelnetClient():
    '初始化屬性'
    def __init__(self):
        self.tn = Telnet()
    '定義login_host函數(shù),用于登陸設(shè)備'
    def login_host(self,ip,username,password,enable=None,verbose=True):
        '連接設(shè)備,try-except結(jié)構(gòu)'
        try:
            self.tn.open(ip,port=23)
        except:
            logging.warning('%s網(wǎng)絡(luò)連接失敗' %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)
        '進(jìn)去特權(quán)模式'
        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登陸失敗,用戶名或密碼錯(cuò)誤' % ip)
            return False

    '定義do_cmd函數(shù),用于執(zhí)行命令'
    def do_cmd(self,cmds):
        '讀取文件,for語(yǔ)句循環(huán)執(zhí)行命令'
        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('命令執(zhí)行結(jié)果:\n %s' %rely)
    '定義logout_host函數(shù),關(guān)閉程序'
    def logout_host(self):
        self.tn.close()

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

3. 運(yùn)行效果

備注:這個(gè)運(yùn)行的效果我只存放了192.168.1.101這個(gè)IP,精簡(jiǎn)一下,為了效果。

4. 報(bào)錯(cuò)效果

4.1 遠(yuǎn)程連接不上

4.2 用戶名和密碼錯(cuò)誤

5. 碎碎語(yǔ)

這些只是一些簡(jiǎn)單的代碼,待優(yōu)化的地方還是很多,先給小伙伴們學(xué)習(xí)一下,telnet協(xié)議是個(gè)不安全的,基本網(wǎng)絡(luò)環(huán)境很少用了,ssh為常用的協(xié)議,安全又好用,下個(gè)文章我給大家介紹python如何使用ssh模塊哈。
本人代碼功夫不深,如有缺陷望指教,多謝。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容