如何绘制IP地址列表为活动或非活动状态并保存到文本文件中

问题描述 投票:1回答:1
import subprocess
import os
import matplotlib.pyplot as plt
def Main ():
    ipaddress = open('ipaddress.txt', 'a')
    with open(os.devnull, "wb") as limbo:
        for n in range(1, 100):
            ip="192.168.1.{0}".format(n)
            result=subprocess.Popen(["ping", "-n", "1", "-w", "200", ip],
                stdout=limbo, stderr=limbo).wait()
            if result:
                print (ip + " inactive")
                ipaddress.write(ip + ' inactive')
            else:
                print (ip + " active")
                ipaddress.write(ip + ' Acive')
    ip = ip.split('\n')
    ip = [float(f) for f in ip]
    slice_labels = ['Active', 'Inactive']
    # Create a pie chart from the values.
    plt.pie(ip, labels=slice_labels)
    # Add a title.
    plt.title('IP address activity')
    # Display the pie chart.
    plt.show()
Main()

代码将打印到终端并写入文本文件,但是它没有绘制饼图。另外,我正在尝试弄清楚如何允许用户选择以是或否的方式保存到文本文件,而不是像当前设置那样仅强制写入,我是否会添加另一个嵌套的if语句?

python matplotlib python-3.7
1个回答
0
投票

这对我有用:

import subprocess
import matplotlib.pyplot as plt
from pathlib import Path
from collections import Counter

addresses = Path('ipaddress.txt')
counter = Counter(a=0, i=0)

with addresses.open('w') as f:
    for n in range(1, 100):
        ip = f'192.168.0.{n}'

        result = subprocess.Popen(
            ['ping', '-n', '1', '-w', '200', ip],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        ).wait()

        if result:
            print(f'{ip} inactive')
            f.write(f'{ip} inactive\n')
            counter.update('i')
        else:
            print(f'{ip} active')
            f.write(f'{ip} active\n')
            counter.update('a')

labels = ['Active', 'Inactive']
plt.pie(counter.values(), labels=labels)
plt.title('IP address activity')
plt.show()

希望对您有帮助。

© www.soinside.com 2019 - 2024. All rights reserved.