“Ping.py”的版本间的差异

来自linux中国网wiki
跳到导航 跳到搜索
docker>Evan
 
(导入1个版本)
 

2019年10月14日 (一) 13:52的最新版本

from __future__ import print_function
import subprocess
import threading
# ping -c 1 ip_address 
def is_reacheable(ip):
    if subprocess.call(["ping","-c","1",ip]):
        print("{0} is  unreacheable".format(ip))
    else:
        print("{0} is alive".format(ip))

'''
subprocess.call 成功是返回0,而python中 0 是不成功
def is_reacheable(ip):
    if subprocess.call(["ping","-c","1",ip]):
        print("{0} is alive".format(ip))
    else:
        print("{0} is unreacheable".format(ip))
'''

def main():
    with open('ips.txt') as f:
        lines = f.readlines()
        threads = []
        for line in lines:
            thr = threading.Thread(target=is_reacheable,args=(line,))
            thr.start()
            threads.append(thr)

        for thr in threads:
            thr.join() #阻塞直到队列中的所有项目全被 删除和处理为止

if __name__ == '__main__':
    main()


'''
解说
print_function 新的print是一个函数,如果导入此特性,之前的print语句就不能用了。

https://www.cnblogs.com/ksedz/p/3190208.html  python的__future__模块

from __future__ import print_function
在python2的环境下,超前使用python3的print函数。

https://zhuanlan.zhihu.com/p/28641474

'''

#ping_with_queue.py
from __future__ import print_function
import subprocess
import threading
from Queue import Queue
from Queue import Empty

def call_ping(ip):
    if subprocess.call(["ping", "-c", "1", ip]):
        print("{0} is alive".format(ip))
    else:
        print("{0} is unreacheable".format(ip))

def is_reacheable(q):
    try:
        while True:
            ip = q.get_nowait()
            call_ping(ip)
    except Empty:
        pass

def main():
    q = Queue()
    with open('ips.txt') as f:
        for line in f:
            q.put(line)

    threads = []
    for i in range(10):
        thr = threading.Thread(target=is_reacheable, args=(q,))
        thr.start()
        threads.append(thr)

    for thr in threads:
        thr.join()

if __name__ == '__main__':
    main()

#!/usr/bin/python
#别人改进的版本 auther: Jacky
#date: 2016-08-01
#filename: ping_ip.py


import os,sys
import subprocess,cmd

def subping():
    f = open("ip_list.txt","r")

    lines = f.readlines()
    for line in lines:
        line=line.strip('\n')
        ret = subprocess.call("ping -c 2 -w 5 %s" % line,shell=True,stdout=subprocess.PIPE)
        if ret == 0:
            str = '%s is alive' % line
            print str
        elif ret == 1:
            str = '%s is not alive' % line
            print str
    f.close()


subping()
#http://blog.51cto.com/jackyxin/1834196 使用python编写批量ping主机脚本

see also

python:threading.Thread类的使用详解