1.shell脚本实现
#!/bin/bash
for i in ` seq 125 135`
do
ip= "192.168.154.$i "
if ping $ip -c 1 & > /dev/null
then
echo "$ip is alive."
else
echo "$ip is not"
fi
done
2.python多线程实现,为每一个ip创建一个线程
import subprocess
import threading
alives = [ ]
def is_reacheable ( ip) :
if subprocess. call( [ "ping" , "-c" , "1" , ip] ) == 0 :
print ( "{0} is alive." . format ( ip) )
alives. append( ip)
else :
print ( "{0} is not." . format ( ip) )
def main ( ) :
threads = [ ]
for i in range ( 100 , 200 ) :
ip = "192.168.154." + str ( i)
thr = threading. Thread( target= is_reacheable, args= ( ip, ) )
thr. start( )
threads. append( thr)
for thr in threads:
thr. join( )
if __name__ == "__main__" :
main( )
print ( alives)
3.python多线程实现,创建10个线程,并使用队列解决多线程之间的并发问题
import subprocess
import threading
from queue import Queue
from queue import Empty
alives = [ ]
def call_ping ( ip) :
if subprocess. call( [ "ping" , "-c" , "1" , ip] ) == 0 :
print ( "{0} is alive." . format ( ip) )
alives. append( ip)
else :
print ( "{0} is not." . format ( ip) )
def is_reacheable ( q) :
try :
while True :
ip = q. get_nowait( )
call_ping( ip)
except Empty:
pass
def main ( ) :
threads = [ ]
q = Queue( )
for i in range ( 100 , 200 ) :
ip = "192.168.154." + str ( i)
q. put( ip)
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( )
print ( alives)