python - Splitting file with contains similar lines -
i have file contains information related many interfaces. example has 2 simplicity.
i need able split different variables intend use later. example, text below i'd create variables called eth1_ip has value of 10.196.135.30, eth1_mask variable of 255.0.0.0, eth2_ip value of 192.168.4.2 etc.
i've been going through different "split" , "readfiles" scenarios haven't been able nail down.
i'm new python , tips appreciated. thank you.
eth1: flags: (0x1043) broadcast multicast trailers arp running type: gigabit_ethernet inet is: 10.196.135.30 vlan: 0 netmask: 255.0.0.0 ethernet address 00:08:25:21:f8:a0 metric 0: maximum transfer unit size 1500 eth2: flags: (0x1003) broadcast multicast trailers arp type: unknown_type inet is: 192.168.4.2 vlan: 0 ethernet address 00:08:25:21:f8:a1 metric 0: maximum transfer unit size 1500 my first attempt included ideas such this:
#!/usr/bin/python import re, os, sys, fnmatch import telnetlib import sys import time import difflib import shutil def gleen_macs(): text = open('show_interfaces.txt', 'r') line in text.readlines(): #print line if re.match('( ethernet address)(.*)', line): values = line.split('is') print values[1] def menu(): get_macs() menu() i concentrating on mac first. can split them can't assign them variable wish. (the "get_macs()" function telnetlib bit used generate file. working wish , not included here).
just step through file, keywords in each line, if line has need extract it, save in dictionary,
results = dict() open('eth.txt') f: line in f: line = line.strip() if line.endswith(':') , not line.startswith('metric'): eth = line[:-1] elif line.startswith('inet'): line = line.split(':') ip, _ = line[1].split() results[eth + '_ip'] = ip elif line.startswith('netmask'): _, mask = line.split(':') mask = mask.strip() results[eth + '_mask'] = mask >>> results {'eth2_ip': '192.168.4.2', 'eth1_ip': '10.196.135.30', 'eth1_mask': '255.0.0.0'} >>>
Comments
Post a Comment