首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python pinging本地IP

Python pinging本地IP
EN

Stack Overflow用户
提问于 2016-08-05 01:35:58
回答 1查看 272关注 0票数 1

所以昨天我在练习我过去几天学到的东西,并决定创建一个脚本来扫描本地网络中的所有in,并检查哪些in正在被使用。

我使用子进程使用带有给定超时的"ping“命令,以及其他一些库,如docopt、线程和时间,用于处理命令行参数、线程、等待代码等常见任务。

脚本如下:

代码语言:javascript
复制
""" 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)

我遇到的问题是,尽管我为ping命令设置了超时(以毫秒为单位),但由于某些原因,一些线程没有完成。我暂时修复了这个问题,将所有线程设置为守护进程,并在程序结束后等待两次超时(main中的最后几行),但这并不能像预期的那样工作,一些线程在休眠后仍未完成。

这是与ping命令本身有关,还是我的设计有问题?

安息吧!

EN

回答 1

Stack Overflow用户

发布于 2016-08-05 02:06:42

Python3.3为subprocess.check_call()实现了timeout=关键字参数

https://docs.python.org/3.3/library/subprocess.html#subprocess.check_call

否则,我将使用另一个线程来确保衍生的命令在超时时间后被终止-例如,请查看以下内容,因此回答:

https://stackoverflow.com/a/6001858/866915

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38773953

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档