【问题标题】:Telnetlib output into text file to be called on as a variable laterTelnetlib 输出到文本文件中,稍后作为变量调用
【发布时间】:2020-02-14 21:51:18
【问题描述】:

我正在尝试创建一个程序,用于在网络中搜索特定的 mac 地址。

当我运行 cisco 命令“show mac-address-table”时,它会给出保存到 MH2 的输出。如果该输出具有“000c”。在其中,所有输出都保存到一个 txt 文件中,我希望我能够根据使用的命令(显示 MAC 地址表与显示 MAC 地址表)过滤并从中提取 VLAN带有mac地址的行的vlan位置可以在左边或右边。我打算稍后弄清楚那部分,但现在我的脚本似乎没有读取文件(它正在获得正确的输出并且其中有一个“000c”条目)我将输入代码下面:

#!/usr/bin/env python3

from time import sleep
import telnetlib
from getpass import getpass



# f is the .txt document that lists the IP's we'll be using.
f = open("devicess.txt")
#
username = input("please provide your username:")
password = getpass()

#
for line in f:
    device = (line)
    print('Starting to collect information, please wait')

#For those devices in the above list, connect and run the below commands
    def loopstart():
        for device in f:
            tn = telnetlib.Telnet()
            tn.open(device, 23, 20)
            #Remove # in the line below for debug
            #tn.set_debuglevel(2000)
            tn.read_until(b"Username:", timeout = 20)
            sleep(.25)
            tn.write(str(username + "\n").encode("ascii"))
            sleep(.25)
            tn.read_until(b"Password: ", timeout = 10)
            sleep(.25)
            tn.write((password + "\n").encode("ascii"))
            sleep(.25)
            #####################################
            #Verify Login attempt below         #
            #####################################
            try:
                enablemode = tn.read_until(b"#")
                if (b"FAIL") in enablemode:
                    print("Bad credentials to " + device)
                    tn.close()
                    sleep(.5)
                elif (b"fail") in enablemode:
                    print("Bad credentials to " + device)
                    tn.close()
                    sleep(.5)
                elif (b"#") in enablemode:
                    print("connection established to " + device)
                    try:
                        tn.write(str("show mac address-table | include 000c.\n").encode('ascii'))
                        sleep(2)
                        MH2 = tn.read_very_eager() 
                        if (b"000c.15") in MH2:
                            try:
                                sleep(.5)
                                mactable = open("mactable.txt", "rb+")
                                mactable.seek(0)
                                mactable.write(MH2)
                                mactable.truncate()
                                OP1 = mactable.read
                                for line in OP1():
                                    CPMAC = (line)    
                                    try:
                                        if (b"000c.15") in CPMAC:
                                            print("line 70 in use")
                                            print((CPMAC) + " this is what vlan the cyber power device should be on")
                                            tn.write(str("show interface vlan" + (CPMAC[:6]) + "\n")).encode("ascii")
                                            tn.read_until(b"Internet Address")
                                            tn.close()
                                        elif (str("All")) in (CPMAC):
                                            print ("CPU has matching MAC, moving to next device")
                                            tn.close()
                                        else:
                                            print("No Cyber power device found on " + device)
                                            tn.close()
                                    except EOFError as e:
                                        print("could not pull vlan from output")
                            except EOFError as e:
                                print("unidentified issue")
            #Execute the following commands in case of invalid command input
                        elif (b"Invalid") in MH2:
                            sleep(.5)
                            try:
                                tn.write(str("show mac-address-table | in 000c.\n").encode('ascii'))
                                sleep(2)
                                MH3 = tn.read_very_eager()
                                if (b"000c.15") in MH3:
                                    print("Line 90 in use")
                                    try:
                                        sleep(.5)
                                        mactable = open("mactable.txt", "r+")
                                        mactable.seek(0)
                                        mactable.write(str(MH3))
                                        OP2 = (mactable.read())
                                        print (type(OP2))
                                        mactable.truncate()
                                        for line in OP2():
                                            CPMAC = (line)
                                            try:  
                                                if ("000c.15") in (CPMAC):
                                                    print((CPMAC) + " this is what vlan the cyber power device should be on")
                                                    tn.write(str("show interface vlan" + (CPMAC[:6])+ "\n").encode("ascii"))
                                                    tn.read_until(b"Internet Address")
                                                    tn.close()
                                                elif (str("All")) in (CPMAC):
                                                    print ("CPU has matching MAC, moving to next device")
                                                    tn.close()
                                                else:
                                                    print("No Cyber power device found on " + device)
                                                    tn.close()
                                            except EOFError as e:
                                                print("could not pull vlan from output")
                                    except EOFError as e:
                                        print("unidentified issue")     
                                elif (b"000c.15") not in MH3:
                                    print ("Cyber power device not found, moving to next device.")
                                    tn.close()
                                else:
                                    print("Unknown Error")
                                    tn.close()

    ##############################
    #        Logout commands     #
    ##############################
                            except EOFError as e:
                                print("Connection closed to " + device)
                        else:
                            tn.write(str("exit\n").encode('ascii'))
                            tn.write(str("exit\n").encode('ascii'))
                            tn.close()
                            print(tn.read_all().decode('ascii'))
                    except EOFError as e:
                        print ("unknown error")
                else:
                    tn.close()
            except EOFError as e:
                print("Connection closed to " + device)
        except Exception as exception:
            print(exception, False)
            tn.close()
    loopstart()
print('script complete') 

"if ("000c.15") in (CPMAC)" 是我认为我遇到问题的代码部分。任何帮助表示赞赏!

【问题讨论】:

  • 请提供您的所有代码。但是,CPMAC 是什么列表/元组?您不需要在该行的变量周围加上括号。
  • 谢谢蒂姆,我已经添加了完整的代码。 CPMAC 应该只是 show mac address-table 或 show mac-address-table 输出中的一行。我能够打开该文件并确保 mac 地址表命令输出进入该文件,因此它肯定可以正常工作。我似乎无法使用 python 搜索文件的行。在 CPMAC 中带有 - if (b"000c.15") 的行: - 应该可以工作,但它似乎没有检测到我已经验证过的行存在。谢谢!

标签: python telnetlib


【解决方案1】:

不太确定您要实现什么,但请检查OP1 = mactable.read 行读取是一个应该写为OP1 = mactable.read() 的函数

【讨论】:

  • 在将 mactable.read 更改为 mactable.read() 后,我的脚本至少会抛出此错误:'bytes' object is not callable False 最终目标是尝试将这些设备添加到我们的 solarwinds 监控中.我不知道这些设备的 IP 地址是什么,所以我需要查找 000c.15 所在的子网。我可以通过识别网络电源设备所在的 vlan 的 IP 并运行“show int vlan (variable from show mac address-table)”在我的网络上执行此操作
  • 文件“mactable.txt”的内容是什么?如果它是一个常规文本文件,则在没有字节标志的情况下读取它,例如 open("mactable.txt", "r")。也尝试在 MH2 = tn.read_very_eager() 之后打印变量 MH2 并检查其类型
  • 此外,您正在尝试写入已在 mactable.write(MH2) 行以读取模式打开的文件
  • MH2 的输出应该类似于本例中的内容:cisco.com/c/m/en_us/techdoc/dc/reference/cli/n5k/commands/…
  • 我回家后会尽快进行这些更改,谢谢。
【解决方案2】:

所以到目前为止,以下是对我有用的,我可以运行命令“show mac address-table”,获取该输出并将其放入文本文件中,通过输出逐行搜索000c.15 并在以后使用该线路进一步输出。我认为重要的是在将输出(字节)写入文本文件之前将其解码为字符串。此外,使用 seek(0) 函数有助于在开始阅读之前将我带回到 txt 文件的开头。 Line.strip 似乎摆脱了所有被解释为线条的空白。不是 100% 确定最后一个。获取该代码以发送命令仍然存在问题,但至少我正在取得进展。感谢大家的帮助。

if (b"000c.15") in MH2:
    print("000c.15 in MH2, line 57")
    try:
        print ("line 59")
        sleep(.5)
        mactable = open("mactable.txt", "w+")
        mactable.seek(0)
        mactable.write(MH2.decode('utf-8'))
        mactable.truncate()
        mactable.seek(0)
        OP1 = mactable.readlines()
            for line in OP1:
            line = line.strip()
            CPMAC = line

【讨论】:

    猜你喜欢
    • 2014-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-01
    • 1970-01-01
    • 2017-12-05
    • 1970-01-01
    • 2013-07-30
    相关资源
    最近更新 更多