Python ping本地IP
所以昨天我在练习过去几天学到的知识,并决定创建一个脚本来扫描本地网络中的所有IP,并检查正在使用哪些IP 我使用了子进程,在给定的超时时间内使用“ping”命令,以及其他一些库,如docopt、线程和时间,用于处理命令行参数、线程、等待代码等常见任务 以下是脚本:Python ping本地IP,python,linux,multithreading,command-line,timeout,Python,Linux,Multithreading,Command Line,Timeout,所以昨天我在练习过去几天学到的知识,并决定创建一个脚本来扫描本地网络中的所有IP,并检查正在使用哪些IP 我使用了子进程,在给定的超时时间内使用“ping”命令,以及其他一些库,如docopt、线程和时间,用于处理命令行参数、线程、等待代码等常见任务 以下是脚本: """ ipcheck.py - Getting available IPs in a network. Usage: ipcheck.py -h | --help ipcheck.py PREFIX ip
""" ipcheck.py - Getting available IPs in a network.
Usage:
ipcheck.py -h | --help
ipcheck.py PREFIX
ipcheck.py [(-n <pack_num> PREFIX) | (-t <timeout> PREFIX)]
Options:
-h --help Show the program's usage.
-n --packnum Number of packets to be sent.
-t --timeout Timeout in miliseconds for the request.
"""
import sys, os, time, threading
from threading import Thread
from threading import Event
import subprocess
import docopt
ips = [] # Global ping variable
def ping(ip, e, n=1, time_out=1000):
global ips
# FIX SO PLATFORM INDEPENDENT
# Use subprocess to ping an IP
try:
dump_file = open('dump.txt', 'w')
subprocess.check_call("ping -q -w%d -c%s %s" % (int(time_out), int(n), ip),
shell=True, stdout=dump_file, stderr=dump_file)
except subprocess.CalledProcessError as err:
# Ip did not receive packets
print("The IP [%s] is NOT AVAILABLE" % ip)
return
else:
# Ip received packets, so available
print("The IP [%s] is AVAILABLE" % ip)
#ips.append(ip)
finally:
# File has to be closed anyway
dump_file.close()
# Also set the event as ping finishes
e.set()
ips.append(1)
def usage():
print("Helped init")
def main(e):
# variables needed
timeout = 1000
N_THREADS = 10
# Get arguments for parsing
arguments = docopt.docopt(__doc__)
# Parse the arguments
if arguments['--help'] or len(sys.argv[1:]) < 1:
usage()
sys.exit(0)
elif arguments['--packnum']:
n_packets = arguments['--packnum']
elif arguments['--timeout']:
timeout = arguments['--timeout']
prefix = arguments['PREFIX']
# Just an inner function to reuse in the main
# loop.
def create_thread(threads, ip, e):
# Just code to crete a ping thread
threads.append(Thread(target=ping, args=(ip, e)))
threads[-1].setDaemon(True)
threads[-1].start()
return
# Do the threading stuff
threads = []
# Loop to check all the IP's
for i in range(1, 256):
if len(threads) < N_THREADS:
# Creating and starting thread
create_thread(threads, prefix+str(i), e)
else:
# Wait until a thread finishes
e.wait()
# Get rid of finished threads
to_del = []
for th in threads:
if not th.is_alive(): to_del.append(th)
for th in to_del: threads.remove(th)
# Cheeky clear init + create thread
create_thread(threads, prefix+str(i), e)
e.clear()
time.sleep(2*timeout/1000) # Last chance to wait for unfinished pings
print("Program ended. Number of threads active: %d." % threading.active_count())
if __name__ == "__main__":
ev = Event()
main(ev)
“ipcheck.py-在网络中获取可用IP。
用法:
ipcheck.py-h |--帮助
ipcheck.py前缀
ipcheck.py[(-n前缀)|(-t前缀)]
选项:
-h—帮助显示程序的使用情况。
-n—要发送的数据包数。
-t—请求的超时(以毫秒为单位)。
"""
导入系统、操作系统、时间、线程
从线程导入线程
从线程导入事件
导入子流程
导入docopt
ips=[]#全局ping变量
def ping(ip、e、n=1,超时=1000):
全球IP
#修正,使平台独立
#使用子流程ping一个IP
尝试:
dump_file=open('dump.txt','w')
子进程检查调用(“ping-q-w%d-c%s%s”%(int(超时)、int(n)、ip),
shell=True,stdout=dump\u文件,stderr=dump\u文件)
除subprocess.CalledProcessError作为错误外:
#Ip没有收到数据包
打印(“IP[%s]不可用”%IP)
返回
其他:
#Ip接收到数据包,因此可用
打印(“IP[%s]可用”%IP)
#附加(ip)
最后:
#无论如何,文件都必须关闭
dump_file.close()
#还将事件设置为ping结束
e、 集合()
ips.append(1)
def用法():
打印(“帮助初始化”)
def总管(e):
#所需变量
超时=1000
N_螺纹=10
#获取用于解析的参数
参数=docopt.docopt
#解析参数
如果参数['--help']或len(sys.argv[1:])<1:
用法()
系统出口(0)
elif参数['--packnum']:
n_packets=参数['--packnum']
elif参数['--timeout']:
超时=参数['--timeout']
prefix=参数['prefix']
#只是一个内部函数,可以在主应用程序中重用
#循环。
def创建_线程(线程、ip、e):
#只需编写一个ping线程
append(线程(target=ping,args=(ip,e)))
线程[-1]。setDaemon(True)
线程[-1]。开始()
返回
#做穿线的工作
线程=[]
#循环以检查所有IP
对于范围(1256)内的i:
如果len(螺纹)
我遇到的问题是,尽管我正在为ping命令设置一个超时(以毫秒为单位),但由于某些原因,某些线程没有完成。我暂时修复了这个问题,将所有线程设为守护线程,并在程序完成后等待两次超时(main中的最后几行),但这并没有按预期工作,一些线程在睡眠后仍然没有完成
这是与命令ping本身有关还是我的设计中存在问题
和平 Python3.3为
子流程实现了一个timeout=
关键字参数
否则,我将使用另一个线程来确保生成的命令在超时后被终止-即,请参见以下答案:
Python3.3为子流程实现了一个timeout=
关键字参数。check\u call()
:
否则,我将使用另一个线程来确保生成的命令在超时后被终止-即,请参见以下答案:
您是否尝试让它在shell(cmd)命令中执行此操作?是的,我在shell上运行了此命令,但它从未超过超时时间。这就是-w命令存在的原因,因此它等待响应的时间不会超过这个时间。但在代码中,它有时似乎仍然会重复这个过程,并且不会终止。嗯,我明白了。我更喜欢使用批处理或C#来实现与互联网相关的功能。在某种程度上,您的脚本运行不平稳。您应该调试它,并让它编写一个脚本正在执行的TXT文件。当它检查您的错误时,您应该看到发生了什么情况。是通过ip地址还是通过名称指定的目标主机?我已经检查了ping源,它在设置截止时间计时器之前执行DNS查找。因此,如果DNS查找缓慢,ping命令可以在截止日期之后运行。您是否尝试让它在shell(cmd)命令中运行?是的,我在shell上运行了该命令,但它从未超过超时时间。这就是-w命令存在的原因,因此它等待响应的时间不会超过这个时间。但在代码中,它有时似乎仍然会重复这个过程,并且不会终止。嗯,我明白了。我更喜欢使用批处理或C#来实现与互联网相关的功能。在某种程度上,您的脚本运行不平稳。您应该调试它,并让它编写一个脚本正在执行的TXT文件。当它检查您的错误时,您应该看到发生了什么情况。是通过ip地址还是通过名称指定的目标主机?我已经检查了ping源,它在设置截止时间计时器之前执行DNS查找。因此,如果DNS查找缓慢,ping命令可以在截止日期之后运行。谢谢!!我正在使用Python2.7,但我可以