Created
June 29, 2017 12:01
-
-
Save imfht/f54cb42d1ba531ec220520d857827cc8 to your computer and use it in GitHub Desktop.
Python ping temp file
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
# @Time : 2017/6/29 下午6:33 | |
# @Auth : fiht | |
# @File : PyPing.py | |
# @Purpose : Python Ping | |
import platform | |
import subprocess | |
def ping_and_print(host): | |
def ping(): | |
""" | |
Returns True if host responds to a ping request | |
""" | |
# Ping parameters as function of OS | |
ping_str = "-n 1" if platform.system().lower() == "windows" else "-c 1" | |
args = "ping " + " " + ping_str + " " + host | |
need_sh = False if platform.system().lower() == "windows" else True | |
# Ping | |
return subprocess.call(args, shell=need_sh, stdout=subprocess.PIPE) == 0 | |
print 'enter %s'%host | |
response = ping() | |
if response == 0: | |
print '%s is alive!' % host | |
else: | |
print '%s is die!' % host | |
def ping_single_thread(ip_list): | |
for ip in ip_list: | |
ping_and_print(ip) | |
def ping_multi_thread(ip_list, thread_num): | |
import Queue | |
import threading | |
def my_ping(): | |
while my_que.not_empty: # 队列空了没有? | |
ip = my_que.get() # pop an item | |
ping_and_print(ip) | |
my_que = Queue.Queue() | |
for i in ip_list: my_que.put(i) | |
t_list = [threading.Thread(target=my_ping) for i in range(thread_num)] | |
for t in t_list: | |
t.start() | |
def ping_multi_thread_use_pool(ip_list, thread_num=10): | |
from multiprocessing.dummy import Pool as ThreadPool | |
pool = ThreadPool(processes=thread_num) | |
pool.map(ping_and_print, ip_list) | |
pool.close() | |
pool.join() | |
if __name__ == '__main__': | |
ips = ['202.194.14.%s' % i for i in range(1, 255)] | |
# ping_single_thread(ips) | |
# ping_multi_thread(ips, 10) | |
# ping_multi_thread_use_pool(ips) | |
pass |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment