在Python中读取IP地址

时间:2015-05-26 23:48:58

标签: python ip

我正在使用Python脚本(由同事编写),该脚本接收输出文件并擦除ping命令的IP地址和结果以确定可达性状态。问题:脚本正在刮取子网掩码而不是主机IP。我不明白为什么正则表达式与IP地址不匹配。下面是代码和脚本生成的输出文件示例:

enter code here


import glob
import re
from tkinter.filedialog import askdirectory
from tkinter import Tk
import os
import ntpath

new_file = []
results_file = []
success_file = []
failure_file = []
new_count = 0
regex_clean = re.compile('ip address')
regex_source = re.compile('ip address')
regex_destination = re.compile('chos to')
regex_success = re.compile('!')
regex_failure = re.compile('\.\.\.\.\.|U\.U\.U')
regex_ip_address = re.compile('\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}')
regex_final_success = re.compile('SUCCESS')
regex_final_failure = re.compile('FAILURE')


def find_files(files_directory):
    file_list = []
    os.chdir(files_directory)
    for file in glob.glob("*.txt"):
        # print(files_directory + '/' + file)
        file_list.append(files_directory + '/' + file)
    return file_list


def clean_data(file):
    with open(file, 'r') as f:
        h = f.readlines()
        for num, line in enumerate(h):
            if regex_clean.search(line) is not None:
                for line2 in h[num-1:num+12]:
                    new_file.append(line2)
                    # print(new_file)
    return new_file


def find_results(new_file):
    for num, line in enumerate(new_file):
        if regex_success.search(line) is not None:
            test_status = 'SUCCESS!'
            if test_status:
                results_file.append('Test Status: ' + test_status)
            # print(results_file)
        if regex_failure.search(line) is not None:
            test_status = 'FAILURE!'
            if test_status:
                results_file.append('Test Status: ' + test_status)
            # print(results_file)
        if regex_source.search(line) is not None:
            source_address = regex_ip_address.findall(line)
            if source_address:
                for ip in source_address:
                    results_file.append('Configured Address: ' + ip)
            # print(results_file)
        if regex_destination.search(line) is not None:
            destination_address = regex_ip_address.findall(line)
            if destination_address:
                for ip in destination_address:
                    results_file.append('Destination Address: ' + ip)
            # print(results_file)
    return results_file


def create_final_files(results_file):
    for num, line in enumerate(results_file):
        # print(line)
        # print("1")
        if regex_final_success.search(line) is not None:
            for line2 in results_file[num-2:num+1]:
                success_file.append(line2)
                # print('SUCCESS FILE')
                # print("2")
                # print(success_file)
                # print('SUCCESS FILE')
        elif regex_final_failure.search(line) is not None:
            for line3 in results_file[num-2:num+1]:
                failure_file.append(line3)
                # print('FAILURE FILE')
                # print("3")
                # print(failure_file)
                # print('FAILURE FILE')
    return success_file, failure_file


def clean_filename(file):
    head, tail = ntpath.split(file)
    return tail


def create_output_files(success_file, failure_file, save_directory, filename):
    success_filename = save_directory + "/SUCCESS_FILE.txt"
    failure_filename = save_directory + "/FAILURE_FILE.txt"

    with open(success_filename, 'a') as f:
        f.write("\n\n")
        f.write("SOURCE FILE: %s\n" % filename)
        f.write("\n")
        for item in success_file:
            f.write("%s\n" % item)

    with open(failure_filename, 'a') as f:
        f.write("\n\n")
        f.write("SOURCE FILE: %s\n" % filename)
        f.write("\n")
        for item in failure_file:
            f.write("%s\n" % item)


if __name__ == '__main__':
    root = Tk()
    print('Welcome to the quick REGEX script!')
    print('This will take ping outputs and return the device IP addresses, and successes, failures in two files.\n')
    print('Select directory containing ping files:')
    files_directory = askdirectory()
    print('FILE DIRECTORY: ' + files_directory)
    print('\n')
    print('Select directory to use for created files:')
    save_directory = askdirectory()
    print('SAVE DIRECTORY: ' + save_directory)
    file_list = find_files(files_directory)
    file_count = len(file_list)
    print('TOTAL FILES: ' + str(file_count))
    # print(file_list)
    for n, file in enumerate(file_list):
        new_count = new_count + 1
        percent_complete = (new_count / file_count) * 100
        print('PERCENT COMPLETE: ' + str(percent_complete) + '%')
        new_file = []
        results_file = []
        success_file = []
        failure_file = []
        # print(type(file))
        # print(file)
        new_file = clean_data(file)
        results_file = find_results(new_file)
        results_file = find_results(new_file)
        # print('RESULTS FILE')
        # print (results_file)
        # print('END OF RESULTS FILE')
        success_file, failure_file = create_final_files(results_file)
        # print('SUCCESS FILE')
        # print(success_file)
        # print('END OF SUCCESS FILE')
        # print('FAILURE FILE')
        # print(failure_file)
        # print('END OF FAILURE FILE')
        filename = clean_filename(file)
        # print('FILE NAME: ' + filename)
        create_output_files(success_file, failure_file, save_directory, filename)
    print('COMPLETE!')
    sleep(5)

    root.destroy()

源文件示例:

sh run | include ip address
 ip address AAA.BBB.CCC.136 255.255.255.128
ping AAA.BBB.67.97

Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to AAA.BBB.67.97, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 142/142/143 ms
ping AAA.BBB.75.97

Type escape sequence to abort.
Sending 5, 100-byte ICMP Echos to AAA.BBB.75.97, timeout is 2 seconds:
!!!!!
Success rate is 100 percent (5/5), round-trip min/avg/max = 134/134/135 ms

示例脚本输出:

Configured Address: 255.255.255.192
Destination Address: AAA.BBB.67.97
Test Status: SUCCESS!
Configured Address: 255.255.255.192
Destination Address: AAA.BBB.67.97
Test Status: SUCCESS!
Test Status: SUCCESS!
Destination Address: AAA.BBB.75.97
Test Status: SUCCESS!
Configured Address: 255.255.255.192
Destination Address: AAA.BBB.67.97
Test Status: SUCCESS!
Configured Address: 255.255.255.192
Destination Address: AAA.BBB.67.97
Test Status: SUCCESS!
Test Status: SUCCESS!
Destination Address: AAA.BBB.75.97
Test Status: SUCCESS!

1 个答案:

答案 0 :(得分:0)

  

脚本正在抓取子网掩码而不是主机IP。   我不明白为什么正则表达式与IP地址不匹配。

您的正则表达式正在查找用点分隔的3个十进制数字(由1到3位数字组成)。所以它找到子网掩码" 255.255.255.192"虽然它没有找到" AAA.BBB.67.97"。

顺便说一句,字符串如" AAA.BBB.67.97"是一个IP地址。