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

2024-04-27 13:57:47 发布

您现在位置:Python中文网/ 问答频道 /正文

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()

代码打印到终端并写入文本文件,但它没有绘制饼图。此外,我还试图弄清楚如何允许用户选择以yes或no的形式保存到文本文件中,而不是在当前设置时强制写入,我是否会添加另一个嵌套的if else语句?你知道吗


Tags: inimportipforlabelsosmainas
1条回答
网友
1楼 · 发布于 2024-04-27 13:57:47

这对我有用:

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.1.{n}'

        cmd = subprocess.run(
            ['ping', '-n', '1', '-w', '200', ip],
            stdout=subprocess.DEVNULL,
            stderr=subprocess.DEVNULL
        )

        if cmd.returncode:
            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()

希望对你有帮助。你知道吗

相关问题 更多 >