對python判斷ip是否可達的實例詳解
更新時間:2019年01月31日 10:37:56 作者:你這只豬兒蟲
今天小編就為大家分享一篇對python判斷ip是否可達的實例詳解,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
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ā)送兩個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來優(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()#當隊列為空,不等待 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是否可達的實例詳解就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
Linux 發(fā)郵件磁盤空間監(jiān)控(python)
這篇文章主要介紹了Linux發(fā)郵件磁盤空間監(jiān)控功能,python實現,需要的朋友可以參考下2016-04-04python打包為linux可執(zhí)行文件的詳細圖文教程
這篇文章主要給大家介紹了關于python打包為linux可執(zhí)行文件的詳細圖文教程,本文介紹的方法可以輕松地將Python代碼變成獨立的可執(zhí)行文件,需要的朋友可以參考下2024-02-02Keras構建神經網絡踩坑(解決model.predict預測值全為0.0的問題)
這篇文章主要介紹了Keras構建神經網絡踩坑(解決model.predict預測值全為0.0的問題),具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-07-07