对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 常用的基础函数

Python: 1. print()函数:打印字符串 2. raw_input()函数:从用户键盘捕获字符 3. len()函数:计算字符长度 4. format(12.3654,'6....

详解Python3 pickle模块用法

pickle(python3.x)和cPickle(python2.x的模块)相当于java的序列化和反序列化操作。 常采用下面的方式使用: import pickle pickle...

python hook监听事件详解

python hook监听事件详解

本文实例为大家分享了python hook监听事件的具体代码,供大家参考,具体内容如下 # -*- coding: utf-8 -*- # # by oldj http://ol...

Python内置方法实现字符串的秘钥加解密(推荐)

Python内置方法实现字符串的秘钥加解密(推荐)

在实际编程开发中,我们会使用到各类的加密算法来对数据和信息进行加密。比如密码中比较常见的MD5加密,以及AES加密等等。 对于密码认证来说,MD5加密是比较适合的,因为其不需要接触到明文...

Mac 上切换Python多版本

Mac 上切换Python多版本

Mac上自带了Python2.x的版本,有时需要使用Python3.x版本做开发,但不能删了Python2.x,可能引起系统不稳定,那么就需要安装多个版本的Python。 1、安装Pyt...