gpt4 book ai didi

python - 如何将 IP 地址列表绘制为事件或非事件状态并保存到文本文件

转载 作者:行者123 更新时间:2023-12-01 06:50:31 24 4
gpt4 key购买 nike

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 else 语句吗?

最佳答案

这对我有用:

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

希望对您有所帮助。

关于python - 如何将 IP 地址列表绘制为事件或非事件状态并保存到文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59026573/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com