拆分包含类似行的文件

2024-05-19 00:23:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个包含许多接口相关信息的文件。为了简单起见,我的例子只有两个。你知道吗

我需要能够分裂成不同的变量,我打算稍后使用。例如,在下面的文本中,我想创建名为eth1_ip的变量,其值为10.196.135.30,eth1_mask的变量为255.0.0.0,eth2_ip的值为192.168.4.2等等

我已经经历了不同的“分割”和“读取文件”场景,但还没能确定下来。你知道吗

我是python新手,任何提示都将不胜感激。非常感谢。你知道吗

eth1:  
     Flags: (0x1043) UP BROADCAST MULTICAST TRAILERS ARP RUNNING   
     Type: GIGABIT_ETHERNET  
     inet is: 10.196.135.30 Vlan: 0  
     Netmask: 255.0.0.0  
     Ethernet address is 00:08:25:21:f8:a0  
     Metric is 0:  
     Maximum Transfer Unit size is 1500    

eth2:  
     Flags: (0x1003) UP BROADCAST MULTICAST TRAILERS ARP   
     Type: UNKNOWN_TYPE  
     inet is: 192.168.4.2 Vlan: 0  
     Ethernet address is 00:08:25:21:f8:a1  
     Metric is 0:  
     Maximum Transfer Unit size is 1500  

我的第一次尝试包括这样的想法:

#!/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')
    for line in text.readlines():
        #print line   
        if re.match('(     Ethernet address)(.*)', line):
            values = line.split('is')
            print values[1]

def menu():
    get_macs()

menu()

我先把注意力集中在mac上。我可以拆分它们,但不能按我的意愿将它们赋给变量。(“get\u macs()”函数只是我用来生成文件的telnetlib位。这是我希望的工作,不包括在这里)。你知道吗


Tags: 文件importipisaddresslineeth1flags
2条回答
with open('interfaces.txt') as infile:
    # Each interface must be separated by a blank line as in the sample
    interfaces = infile.read().split('\n\n')

interfaces = map(str.splitlines, interfaces)
interfaces = {lines[0][:-1]: [line.strip() for line in lines[1:]]
              for lines in interfaces}


def interface_value(interface_name, line_prefix):
    # Make this argument case-insensitive to make the function easier to use
    line_prefix = line_prefix.lower()
    lines = [line for line in interfaces[interface_name]
             if line.lower().startswith(line_prefix)]
    if len(lines) == 0:
        raise ValueError('No lines found with given prefix')
    if len(lines) > 1:
        raise ValueError('Multiple lines found with given prefix: \n %s' % lines)
    return lines[0][len(line_prefix):].strip(': ')


eth1_flags = interface_value('eth1', 'flags')
eth2_mtu = interface_value('eth2', 'Maximum Transfer Unit size is')

print(eth1_flags)
print(eth2_mtu)

输出:

(0x1043) UP BROADCAST MULTICAST TRAILERS ARP RUNNING
1500

我将让您执行额外的解析,比如从"10.196.135.30 Vlan: 0"中获取IP。你知道吗

只需一步一步地浏览文件,在每行中查找关键字,如果某行有您需要的内容,请将其提取出来,保存在字典中

results = dict()
with open('eth.txt') as f:
    for line in f:
        line = line.strip()
        if line.endswith(':') and 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'}
>>>

相关问题 更多 >

    热门问题