对python判断ip是否可达的实例详解

yipeiwu_com5年前Python基础

python中使用subprocess来使用shell

关于threading的用法

from __future__ import print_function
import subprocess
import threading

def is_reachable(ip):
  if subprocess.call(["ping", "-c", "2", ip])==0:#只发送两个ECHO_REQUEST包
    print("{0} is alive.".format(ip))
  else:
    print("{0} is unalive".format(ip))
if __name__ == "__main__":
  ips = ["www.baidu.com","192.168.0.1"]
  threads = []
  for ip in ips:
    thr = threading.Thread(target=is_reachable, args=(ip,))#参数必须为tuple形式
    thr.start()#启动
    threads.append(thr)
  for thr in threads:
    thr.join()

改良 :使用Queue来优化(FIFO)

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", "2", ip])==0:
    print("{0} is reachable".format(ip))
  else:
    print("{0} is unreachable".format(ip))


def is_reachable(q):
  try:
    while True:
      ip = q.get_nowait()#当队列为空,不等待
      call_ping(ip)
  except Empty:
    pass


def main():
  q = Queue()
  args = ["www.baidu.com", "www.sohu.com", "192.168.0.1"]
  for arg in args:
    q.put(arg)

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

if __name__ == "__main__":
  main()

以上这篇对python判断ip是否可达的实例详解就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python使用sklearn库实现的各种分类算法简单应用小结

本文实例讲述了Python使用sklearn库实现的各种分类算法简单应用。分享给大家供大家参考,具体如下: KNN from sklearn.neighbors import KNe...

python实现操作文件(文件夹)

本文实例为大家分享了pyhton操作文件的具体代码,供大家参考,具体内容如下 copy_file 功能:将某个文件夹下的所有文件(文件夹)复制到另一个文件夹 #! python 3...

Python中用Descriptor实现类级属性(Property)详解

上篇文章简单介绍了python中描述器(Descriptor)的概念和使用,有心的同学估计已经Get√了该技能。本篇文章通过一个Descriptor的使用场景再次给出一个案例,让不了解情...

python实现美团订单推送到测试环境,提供便利操作示例

本文实例讲述了python实现美团订单推送到测试环境,提供便利操作。分享给大家供大家参考,具体如下: 背景: 有时候需要在测试环境下一个美团的订单,每次都找一堆的东西,太繁琐,于是写了...

Python datetime时间格式化去掉前导0

Python时间格式化的时候,去掉前导0的: dt = datetime.now() print dt.strftime('%-H') #结果是: '4' 在format s...