标签:
需求:
有一个目录,里面包含一些配置文件。 配置文件名字格式如下:
d1_998
d2_99
d3_90
每一个文件代表一个设备。‘_‘ 前的名字是设备名。 文件内容是设备配置。如下:
api_base install libdapana -> root not damuser da_ui ->centos7 Something some line interface vlan1 ip address 192.168.1.19 no ip redirects shutdown ! interface vlan2 ip address 192.168.1.20 no ip redirect shutdown ! interface e3 ip address 192.168.1.21 no ip redirect not shutdown afasfwe
配置中 interface 开头的表示一个interface配置。 ! 或者空行表示该interface 配置结束 . 我们基于以下规则判断接口是否配置正确
1. 具有no ip redirects
2. 如果不具有 no ip redirects 则必须明确配置shutdown
3. vlan1不关心
要求写一段程序,处理目录下所有设备配置文件。 如果某设备配置错误,则输出 设备名 interface ip
代码如下:
#!/usr/bin/python ################################################################ #Get device name from file name ################################################################ def get_device_name( file_name ): device_name = file_name[ 0 : file_name.index(‘_‘)] return device_name ################################################################ #Get config block list for one file ################################################################ def get_config_block_list(file_name): config_block_list = [] config_block = [] fd = open(file_name)
config_start_flag = False for line in fd.readlines(): if line.lstrip().startswith(‘interface ‘): config_block = [] config_start_flag = True if config_start_flag: config_block.append(line.lstrip().rstrip()) if line.lstrip().rstrip() == ‘!‘ or line == ‘\n‘: config_start_flag = False config_block_list.append(config_block[ : ]) fd.close() return config_block_list ################################################################ #Check one config block based on rules1 ################################################################ def check_config_block_based_on_rule1(config_block): interface_name = config_block[0].split()[1] ip = [ row.split()[2] for row in config_block if row.startswith(‘ip addres‘)][0] if interface_name == ‘vlan1‘: return None no_redirects_flag = True if ‘no ip redirects‘ not in config_block else False shutdown_flag = True if ‘shutdown‘ in config_block else False if no_redirects_flag and not shutdown_flag : return {‘interface_name‘:interface_name,‘ip‘:ip} import os if __name__ == ‘__main__‘: #Get file list path = ‘/home/damuser/Desktop/devices/‘ file_name_list = os.listdir(path) #Go through file list for file_name in file_name_list: device_name = get_device_name(file_name) error_config_list = [] config_block_list = get_config_block_list(path+file_name) for config_block in config_block_list: ret = check_config_block_based_on_rule1(config_block) if ret: error_config_list.append(ret) if error_config_list: for config in error_config_list: print "%s %s %s" %(device_name , config[‘interface_name‘], config[‘ip‘])
运行
[damuser@limingwei myCode]$ ./process_config.py d1 e3 192.168.1.21 d1 e4 192.168.1.22 d2 e2 192.168.1.20 d3 e3 192.168.1.21 d3 e4 192.168.1.22 d3 e55 192.168.1.23
标签:
原文地址:http://www.cnblogs.com/kramer/p/4502883.html