对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二维键值数组生成转json的例子

今天出于需要,要将爬虫爬取的一些数据整理成二维数组,再编码成json字符串传入数据库 那么问题就来了,在php中这个过程很简便 ,类似这样: $arr[$key1][$key2]=...

Django配置MySQL数据库的完整步骤

Django配置MySQL数据库的完整步骤

一、在settings.py中配置 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql',  # 数...

Python自动发送邮件的方法实例总结

Python自动发送邮件的方法实例总结

本文实例讲述了Python自动发送邮件的方法。分享给大家供大家参考,具体如下: python发邮件需要掌握两个模块的用法,smtplib和email,这俩模块是python自带的,只需i...

python获取Linux发行版名称

我必须从Python脚本中获取Linux发行版名称。dist平台模块中有一个方法: import platform platform.dist() 但在我的Arch Linux下...

Python读取csv文件分隔符设置方法

Windows下的分隔符默认的是逗号,而MAC的分隔符是分号。拿到一份用分号分割的CSV文件,在Win下是无法正确读取的,因为CSV模块默认调用的是Excel的规则。 所以我们在读取文件...