對(duì)python判斷ip是否可達(dá)的實(shí)例詳解
更新時(shí)間:2019年01月31日 10:37:56 作者:你這只豬兒蟲
今天小編就為大家分享一篇對(duì)python判斷ip是否可達(dá)的實(shí)例詳解,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
python中使用subprocess來使用shell
from __future__ import print_function
import subprocess
import threading
def is_reachable(ip):
if subprocess.call(["ping", "-c", "2", ip])==0:#只發(fā)送兩個(gè)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,))#參數(shù)必須為tuple形式
thr.start()#啟動(dòng)
threads.append(thr)
for thr in threads:
thr.join()
改良 :使用Queue來優(yōu)化(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()#當(dāng)隊(duì)列為空,不等待
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()
以上這篇對(duì)python判斷ip是否可達(dá)的實(shí)例詳解就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
NumPy對(duì)數(shù)組按索引查詢實(shí)戰(zhàn)方法總結(jié)
數(shù)組的高級(jí)操作主要是組合數(shù)組,拆分?jǐn)?shù)組,tile數(shù)組和重組元素,下面這篇文章主要給大家介紹了關(guān)于NumPy對(duì)數(shù)組按索引查詢的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2022-08-08
Python利用wxPython制作股票價(jià)格查詢工具
在當(dāng)今信息時(shí)代,金融市場(chǎng)是一個(gè)引人注目的話題。本文將介紹如何使用 Yahoo Finance API、yfinance 模塊和 wxPython 庫來創(chuàng)建一個(gè)簡(jiǎn)單的全球股市實(shí)時(shí)價(jià)格查詢工具,希望大家能夠喜歡2023-05-05
詳解python statistics模塊及函數(shù)用法
本節(jié)介紹 Python 中的另一個(gè)常用模塊 —— statistics模塊,該模塊提供了用于計(jì)算數(shù)字?jǐn)?shù)據(jù)的數(shù)理統(tǒng)計(jì)量的函數(shù)。這篇文章重點(diǎn)給大家介紹python statistics 模塊的一些用法,感興趣的朋友跟隨小編一起看看吧2019-10-10
Python數(shù)據(jù)可視化之分析熱門話題“丁克家庭都怎么樣了”
今天小編就以一個(gè)數(shù)據(jù)分析師的視角來向大家講述一下年輕人群體對(duì)于丁克的態(tài)度以及那些丁克家庭他們的想法是怎么樣的?他們是否有過后悔當(dāng)初的決定,需要的朋友可以參考下2021-06-06

