jeudi 29 octobre 2015

python - auditing lines from a file

I am trying to audit a file and store the results for each section, here is the file sample:

-------------- Task 1 -------------- Device Name: hostname_A
Status: Completed
Results: Action completed successfully...

****** Enable Mode Results ******
hostname_A#show run | in abcd
abcd
hostname_A#show ip access-list 1
Standard IP access list 1
    10 permit 1.1.1.1
    20 permit 2.2.2.2
    30 permit 3.3.3.3

-------------- Task 2 -------------- Device Name: hostname_B
Status: Completed
And so on...

And here is the Code I´ve created so far, but struggling to get it working:

with open("file_to_be_audited.txt", "r") as infile:
    with open ('audited_file.txt', "w") as outfile:
        for line in infile:
            if '--- Task' in line:           #seeting a line/section delimiter
                for each_line_in_Task_Block: #trying to check/audit each line of that section
                        device_dict = {}
                        device_dict['hostname'] = re.search("Device Name: (.+)", each_line_in_Task_Block) # trying to store the DeviceName
                        if 'abcd' in line:
                            device_dict['community'] = 'Passed'
                        else:
                            device_dict['community'] = 'Failed'

                        if '2.2.2.2' and '3.3.3.3' in each_line_in_Task_Block:
                            device_dict['ACL'] = 'Passed'
                        else:
                            device_dict['ACL'] = 'Failed'

                    field_order = ('hostname', 'community', 'ACL')
                    for i in field_order:
                        outfile.write(device_dict[i])

There are a lot of '--- Task ---' sections, the idea is to check and store the results of each 'Device Name' in another file. I am trying to get a better and working way of doing it. Any suggestion ? Thank you !

Aucun commentaire:

Enregistrer un commentaire