Python Telnetlib输出到文本文件中,稍后作为变量调用

Python Telnetlib输出到文本文件中,稍后作为变量调用,python,telnetlib,Python,Telnetlib,我有一个程序,我正试图创建的目的是搜索特定的mac地址的网络 当我运行cisco命令“show mac address table”时,它会给出保存到MH2的输出。如果该输出有“000c”。在其中,所有输出都保存到一个txt文件中,我希望能够根据所使用的命令(show mac address table vs show mac address table)过滤并从中提取vlan,因为带有mac地址的线路的vlan位置可能在左侧或右侧。我计划稍后再计算该部分,但目前我的脚本似乎没有读取该文件(该文

我有一个程序,我正试图创建的目的是搜索特定的mac地址的网络

当我运行cisco命令“show mac address table”时,它会给出保存到MH2的输出。如果该输出有“000c”。在其中,所有输出都保存到一个txt文件中,我希望能够根据所使用的命令(show mac address table vs show mac address table)过滤并从中提取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') 

(CPMAC)中的“if”(“000c.15”)是我认为有问题的代码部分。感谢您的帮助

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

,因此以下是迄今为止对我有效的方法,我能够运行命令“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

请提供您的所有代码。然而,什么是CPMAC?列表/元组是什么?您不需要在那一行的变量周围加括号。谢谢Tim,我已经添加了完整的代码。CPMAC应该是showmac地址表或showmac地址表输出的一行。我能够打开该文件,并确保mac地址表命令输出进入该文件,因此它肯定能工作到这一点。我似乎无法用python搜索文件的行。CPMAC:-中带有-if(b“000c.15”)的行应该可以工作,但它似乎没有检测到我验证过的行存在。谢谢将mactable.read更改为mactable.read()后,我的脚本至少抛出了以下错误:“bytes”对象不可调用False最终目标是尝试将这些设备添加到solarwinds监控中。我不知道这些设备的IP地址是什么,所以我需要查找000c.15所在的子网。我可以通过识别cyber power设备所在vlan的IP并运行“show int vlan(来自show mac address table的变量)”文件“mactable.txt”的内容,在我的网络上实现这一点?如果它是一个常规文本文件,则在不带字节标志的情况下读取它,以便打开(“mactable.txt”、“r”)。另外,请尝试在MH2=tn.read_very_eager()之后打印变量MH2,并检查其类型。此外,您正在尝试写入已在mactable行上以读取模式打开的文件。write(MH2)MH2的输出应与本例中的类似:我回家后会尝试进行这些更改,谢谢。