0

I have a program that i'm trying to create for the purpose of searching the network for specific mac addresses.

When I run the cisco command "show mac-address-table" it gives output that's saved to MH2. If that output has "000c." in it all the output is saved into a txt file that i'm hoping i'll be able to filter through and pull the vlan from based on the command used (show mac address-table vs show mac-address-table) as the vlan location for the line with the mac address could be to the left or the right. I'm planning on figuring that part out later, but for now it doesn't seem that my script is reading the file(which is getting the correct output and has a "000c." entry in it) I'll enter the code below:

#!/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)" is the part of the code that I believe i'm having trouble with. any help is appreciated!

  • Please provide all your code. However, what is CPMAC is that list/tuple? You don't need the parenthesis around the variables on that line. – Tim Oct 17 '19 at 23:00
  • Thanks Tim, I've added the complete code. CPMAC should just be a line from the output of show mac address-table or show mac-address-table. I am able to open that file up and ensure that the mac address table command output is going into that file so it definitely works to that point. I just can't seem to search the lines of the file with python.the line with - if (b"000c.15") in CPMAC: - should work but it doesn't seem to detect that line which i've verified is present. Thanks! – andrew lee Oct 18 '19 at 11:32

2 Answers2

0

Not really sure what you are trying to achieve but check the line OP1 = mactable.read read is a function that should be written as OP1 = mactable.read()

Bassosimons
  • 11
  • 1
  • 4
  • After changing mactable.read to mactable.read() my script is at least throwing this error: 'bytes' object is not callable False The end goal is to try and add these devices into our solarwinds monitoring. I have no idea what IP address these devices are so I need to look up the subnet that 000c.15 is on. I can do this on my network by identifying the IP of the vlan that the cyber power device is on and running "show int vlan (variable from show mac address-table)" – andrew lee Oct 18 '19 at 17:32
  • What's the content of file "mactable.txt"? If it's a regular text file read it without the byte flag such that open("mactable.txt", "r"). Also try to print the variable MH2 after MH2 = tn.read_very_eager() and check its type – Bassosimons Oct 19 '19 at 22:11
  • Furthermore you are trying to write to a file that you have opened in read mode on line mactable.write(MH2) – Bassosimons Oct 19 '19 at 22:22
  • The output of MH2 should look like something in this example: https://www.cisco.com/c/m/en_us/techdoc/dc/reference/cli/n5k/commands/show-mac-address-table.html – andrew lee Oct 20 '19 at 17:57
  • I'll try and make those changes shortly when I get home, thanks. – andrew lee Oct 20 '19 at 17:58
  • Confirm if indeed whether the content of MH2 is what you expect for an output – Bassosimons Oct 21 '19 at 07:05
  • So the output of MH2 is indeed the mac address table i'm expecting so we just need to figure out how to read from that file. MH2 is showing as "" – andrew lee Oct 21 '19 at 10:54
  • So I used print statements to narrow down where that error was occurring. I'm still getting 'bytes' object is not callable False and it appears to be triggered by my for statement where I try to cycle through the lines of mactable.txt looking for matching text. – andrew lee Oct 22 '19 at 11:55
0

So the below is what has worked for me so far, I'm able to run the command "show mac address-table", take that output and put it into a text file, search line by line through the output for 000c.15 and use that line for further output later down the road. I think the important thing was to decode the output(bytes) into a string before writing it to the text file. Also, using the seek(0) function was helpful for taking me back to the beginning of the txt file before starting to read. Line.strip seems to get rid of all the white space being interpreted as lines. not 100% sure on that last one. Still having issues with getting that code to send the command but i'm making progress at least. Thanks everyone for your help.

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