首页 > 解决方案 > 需要准确地将文本文件分类为子类别

问题描述

编辑:

该代码准确地提取了路由表并可以请求特定的路由,但是我仍然无法弄清楚如何将路由表分类到特定的组中。当我排序时,它会创建新的文本文件,但内容是错误的。在创建的每个文件中,它只是用路由表的最后一行填充文本文件。这是我当前的代码:

import subprocess
import os
# Open the routing table and keep the same format
def Call_Routing_Table():
    out = subprocess.Popen("route", stdout=subprocess.PIPE)
    out = out.stdout.read().decode('ascii')
    return out.splitlines()

#Sort the Contents of the table into their respective CIDR blocks
def SortCIDRBlocks(text):

    word = "128.0.0.0"
    for line in text:
        if word in line:
             CIDR1 = open("CIDR1.txt","w+")
             CIDR1.write(line)
             line + 1
            
    word = "192.0.0.0"
    for line in text:
        if word in line:
            CIDR2 = open("CIDR2.txt","w+")
            CIDR2.write(line)
            
    word = "224.0.0.0"
    for line in text:
        if word in line:
            CIDR3 = open("CIDR3.txt","w+")
            CIDR3.write(line)
            
    word = "240.0.0.0"
    for line in text:
        if word in line:
            CIDR4 = open("CIDR4.txt","w+")
            CIDR4.write(line)
    
    word = "255.255.255.0"
    for line in text:
        if word in line:
            CIDR24 = open("CIDR24.txt","w+")
            CIDR24.write(line)

def Pull_Specific_Route(text):
    word = input('Enter desired route:')
    for line in text:
        if word in line:
            print(line)

## Set the routing table to variable lines
lines = Call_Routing_Table()

## Call function to sort routing table into CIDR Blocks
SortCIDRBlocks(lines)

Pull_Specific_Route(lines)

标签: pythonsorting

解决方案


这消除了许多不必要的处理,但正如我所说,这只是复制更容易键入的命令route | grep /27

import subprocess

def Call_Routing_Table():
    out = subprocess.Popen("route print", stdout=subprocess.PIPE)
    out = out.stdout.read().decode('ascii')
    return out.splitlines()

def Pull_Specific_Route(text):
    word = input('Enter desired route:')
    for line in text:
        if word in line:
            print(line)

lines = Call_Routing_Table()
Pull_Specific_Route(lines)

推荐阅读