Python programming

SAIDIN_sl

shitlord
44
1
Hey everyone,
-edit-
I'm going to narrow my question down... so below is the code I have for reading the .txt file I have (Router Lab-A Atlanta). I need to draw specific instances of IP addresses from that router config file and print them out.
Do I need separate for loops for every search ? or can I just continue/break the loop ?
How do I code to look for specific IP addresses from the router config ? Specifically, let's say one router config file has the Ethernet ports before the Serial ports or vice versa ? The way I'm coding for the first instance of "version" would set me up for failure if the configuration files fluctuate in format.
sesame = open('sample1.txt', 'r')
contents = sesame.read()

for line in open('sample1.txt'):
if "version" in line:
print (line)
break;
 

LennyLenard_sl

shitlord
195
1
My python is rather rusty, but if you want to parse the file, and extract certain pieces of text, you should look into Regular Expressions.

http://docs.python.org/2/library/re.html

A decentexampleto get started with.

Super powerful (and usable across nearly every programming and scripting language), but rather a pain in the ass to learn IMO.

Using them, you can do case insensitive searches, ignore variable whitespace and deal with a whole bunch of other minor (and not so minor) format variations.

EDIT: Another greatregexsite
 

SAIDIN_sl

shitlord
44
1
Thank you for the links. Regular Expressions are definitely an area I avoid often. Maybe it's time to go down that route.

Here is the code I've made so far, and it works for this particular file. I haven't tested it for others though. The only issue that I'm running into now is for instance this... Both spoilers are the serial/ethernet interfaces. I don't know how to code it so the IDE looks at the work "Ethernet" and copies any integer value after that and prints it out for me. I don't know if that makes sense to you all.
interface Ethernet0/0 This is the Ethernet port e0/0

description connected to Teal-Hub-A-Atlanta

ip address 192.5.5.1 255.255.255.0

full-duplex

ipx network 1A encapsulation SNAP

no mop enabled

Here is the code I've made so far.
sesame = open('sample1.txt', 'r') ;contents = sesame.read()


for hostname in open('sample1.txt'):
if "hostname " in hostname:
print ("The name of the router is : " + hostname)
break;


for version in open('sample1.txt'):
if "version " in version:
print ("The version of this router is : " + version)
break;
print (" ***********************************" + "\n" + "The following allows name to IP address resolution" + "\n" )
for hostb in open('sample1.txt'):
if "ip host lab-b " in hostb:
print (hostb)
break;
for hostc in open('sample1.txt'):
if "ip host lab-c " in hostc:
print (hostc)
break;
for hostd in open('sample1.txt'):
if "ip host lab-d " in hostd:
print (hostd)
break;
for hoste in open('sample1.txt'):
if "ip host lab-e " in hoste:
print (hoste)
break;
for hostf in open('sample1.txt'):
if "ip host lab-f " in hostf:
print (hostf)
break;
 

LennyLenard_sl

shitlord
195
1
I'm not quite sure what you want to do with the output or how exactly you want the output, but this might give you some ideas. As I mentioned, my python is a bit rusty, so not sure if things are done optimally (I write a lot of C#, so I'm pretty sure I'm needlessly using semicolons, but python didn't reject it).

Source code (using regex)
def fileParse():

#1
keyWords = ['hostname', 'version', 'ip host', 'interface']



#for word in keyWords:
# print (word)

file = open('E:\Python\ciscorouter.txt', 'r');
contents = file.readlines();

#for word in contents:
# print (word)

#2
for keyWord in keyWords:
regexWord = "{0}".format(keyWord);
print ("Matching for keyword: {0}".format(regexWord));
#3
for line in contents:
testResult = re.findall(regexWord, line)
length = len(testResult);
#4
if length > 0:
values = re.split("{0}|\\s".format(regexWord), line);
#5
for value in values:
if value:
print("\tSource line: {0}".format(line));
print("\tMatched: {0} with value:\n\t {1}\n\n".format(regexWord, value));

Output:
>>>
Matching for keyword: hostname
Source line: hostname Lab-A-Atlanta

Matched: hostname with value:
Lab-A-Atlanta


Matching for keyword: version
Source line: version 12.1

Matched: version with value:
12.1


Source line: version 2

Matched: version with value:
2


Matching for keyword: ip host
Source line: ip host lab-b 201.100.11.2

Matched: ip host with value:
lab-b


Source line: ip host lab-b 201.100.11.2

Matched: ip host with value:
201.100.11.2


Source line: ip host lab-c 199.6.13.2 199.7.14.2

Matched: ip host with value:
lab-c


Source line: ip host lab-c 199.6.13.2 199.7.14.2

Matched: ip host with value:
199.6.13.2


Source line: ip host lab-c 199.6.13.2 199.7.14.2

Matched: ip host with value:
199.7.14.2


Source line: ip host lab-d 204.204.7.2

Matched: ip host with value:
lab-d


Source line: ip host lab-d 204.204.7.2

Matched: ip host with value:
204.204.7.2


Source line: ip host lab-e 210.93.105.2

Matched: ip host with value:
lab-e


Source line: ip host lab-e 210.93.105.2

Matched: ip host with value:
210.93.105.2


Source line: ip host switch-a 205.7.5.9

Matched: ip host with value:
switch-a


Source line: ip host switch-a 205.7.5.9

Matched: ip host with value:
205.7.5.9


Source line: ip host switch-d 210.93.105.9

Matched: ip host with value:
switch-d


Source line: ip host switch-d 210.93.105.9

Matched: ip host with value:
210.93.105.9


Matching for keyword: interface
Source line: interface Ethernet0/0

Matched: interface with value:
Ethernet0/0


Source line: interface Serial0/0

Matched: interface with value:
Serial0/0


Source line: interface Ethernet0/1

Matched: interface with value:
Ethernet0/1


Source line: interface Serial0/1

Matched: interface with value:
Serial0/1


>>>

#1 Defines a set of keywords to look for
#2 begins a loop through the whole file's contents per keyword
#3 for each line, it does a re.findall() with the current keyword
#4 if the resultant length is > 0, then it thinks it's found the keyword, and splits the line with the keyword and whitespace (\s)
#5 it loops through the split results, and prints it out

So I doubt it's exactly what you're looking for, but it might give an idea of how to nest loops, and using some basic Regex, find, and pick apart lines based on keywords.
Essentially what it does is define a set of keywords. It then loops through the file's contents per each keyword. Per loop, it constructs a basic basic RE. If the length of the RE.findall is > 0, then it then splits that line based on the keyword and white space (\s). Then it loops through those results and prints out the results
 

LennyLenard_sl

shitlord
195
1
Hmm not sure. You've got the file location correct?

Uncomment:

#for word in keyWords:
# print (word)

and

#for word in contents:
# print (word)

Those will print the keywords, as well as every line in the file.

If the first is blank, then your keywords are wrong.

If the second is blank, then your not getting the file contents.
 

SAIDIN_sl

shitlord
44
1
rrr_img_53633.jpg
Ok here is my screen. It didn't format when you posted it on the forum, so I tried to manually do it.
Attachment 53632
 

LennyLenard_sl

shitlord
195
1
My mistake, I forgot the "pass" at the end of the method. Are you calling the fileParse() method? Also forgot to mention you'll need to add "import re" at the top.

Your formatting looks correct except "print ("Matching for keyword: {0}".format(regexWord));" should be indented one more.

Mine looks like this:
rrr_img_53641.png



I'm not too familiar with the various environments python can run in (or how to run it there), I am using PyScripter, so I'm not sure exactly what a file should look like--if, for instance you were running it directly via the python command-line. But in order to get it to work in PyScripter it had the def main() and if __name__ bits already there.

But either way, make sure to add the "pass" at the end of the def, and add "import re" at the top. Then it's just a matter of figuring out how to call fileParse().

What is the name of your IDE (your development environment, the place you're writing this code)?
 

Tenks

Bronze Knight of the Realm
14,163
606
Does this have to be in Python? I'm also not 100% sure what your requirements are or what you're trying to accomplish here. But you could accomplish this with Bash, Python or Groovy all pretty easily if you just want to parse strings and grab values.
 

SAIDIN_sl

shitlord
44
1
Hey Lenny, thank you for your code. Do you mind posting it with the
Code:
 feature please ? My overall intention is to parse hundreds of router configs and grab specific details from them, then consolidate them. The problem I have been running into was how ? The code I made worked perfectly for only the single router config file infront of me. It wasn't scalable whatsoever.