【发布时间】:2016-11-08 17:18:12
【问题描述】:
我正在尝试编写一个脚本,将 ping 发送到 2 个给定范围之间的 ip,并尝试了解它们是否可用。我取得了一些进展,但有些事情我仍然无法解决。例如,我得到了两次输出。如果你能帮助我,这将是完美的,这是我的代码:
import subprocess
ipfirst=input("1st ip:")
iplast=input("2nd ip:")
currentip=""
ip_adresses_list=[]
"""this function may be my problem because i didnt understand the response,result structure if anyone can explain this i'd be appreciated"""
def ip_checker(ip):
response,result=subprocess.getstatusoutput("ping -c1 -w0.5 "+ip)
if (response==0):
print(ip,"ALIVE")
else:
print(ip,"NOT ALIVE")
return ip
""""splitting in order to increase"""
ipfirst=ipfirst.split(".")
ipfirst=list(map(int,ipfirst))
iplast=iplast.split(".")
iplast=list(map(int,iplast))
"""here while loop increases the ipfirst and appends to the list (i used just append at first but it didnt work , it only added the last ipn umber times all ip numbers like ([1.1.1.5],[1.1.1.5],[1.1.1.5],[1.1.1.5])) and my problem may be occuring because of that structure ".copy()" """
while (iplast>ipfirst):
ip_adresses_list.append(ipfirst.copy())
ipfirst[3] = ipfirst[3]+1
ip_adresses_list.append(ipfirst.copy())
if (ipfirst[3]>254):
ipfirst[3]=0
ipfirst[2]=ipfirst[2]+1
ip_adresses_list.append(ipfirst.copy())
if (ipfirst[2]>254):
ipfirst[2]=0
ipfirst[1]=ipfirst[1]+1
ip_adresses_list.append(ipfirst.copy())
if(ipfirst[1]>254):
ipfirst[1]=0
ipfirst[0]=ipfirst[0]+1
ip_adresses_list.append(ipfirst.copy())
"""i rearrange the list in order to get ip structure(num1.num2.num3.num4 like that) and i mixed it with ping function(ip_checker())"""
for i in ip_adresses_list:
ip_indice1=i[0]
ip_indice2=i[1]
ip_indice3=i[2]
ip_indice4=i[3]
currentip=str(str(ip_indice1)+"."+str(ip_indice2)+"."+str(ip_indice3)+"."+str(ip_indice4))
ip_checker(currentip)
如果我运行这段代码,我会得到并输出这样的 icant 明白为什么除了第一个 ip 之外,它会在每个 ip 上 ping 两次
144.122.152.10 NOT ALIVE
144.122.152.11 ALIVE
144.122.152.11 ALIVE
144.122.152.12 ALIVE
144.122.152.12 ALIVE
144.122.152.13 ALIVE
144.122.152.13 ALIVE
【问题讨论】:
-
您确实需要添加空格。这太密集了,很难阅读。
-
到处都是神奇的数字也使这很难推理,但您似乎使用了一种极其迂回的方式来实现您的目标。除非我遗漏了什么,否则循环只需要像 4 行。
标签: python-3.x ip subprocess output ping