歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Python檢測服務器是否ping通

Python檢測服務器是否ping通

日期:2017/3/1 9:31:45   编辑:Linux編程

Python檢測服務器是否ping通的2種方法:

1、第一種比較挫,就是用ping,python調用shell,這個適用於較少的服務器數量,幾百台已經很慢了(當然是說python同步的方法,要是nodejs異步方式還是很快的,但是nodejs CPU計算不行,所以嘗試了下只能200台左右的服務器可以同時ping,再多的話程序也會崩掉)

shell腳本再簡單不過了,ping.sh如下:

#!/bin/bash
PING=`ping -c 3 $1 | grep '0 received' | wc -l`
echo $PING

其實很簡單,ping 3個包,只要ping通,上述返回的結果就不是0。$1是傳入的第一個參數,即IP

思路很簡單的,從數據庫讀出IP 列表,然後調用上述腳本:

#檢查ip能否ping通
#0:正常,1:ping不通
def check_ip_ping():
record = get_ip() #從數據庫中讀取的IP列表
for i in range(0,len(record)):
p = subprocess.Popen([r'./ping.sh',record[i]],stdout=subprocess.PIPE)
result = p.stdout.read()
Status = 0
if result =='1\n':
Status = 1
#print i,record[i],'----ping failed----'
else:
ping_ok.append(record[i])
#print i,record[i],'----ping success----'
mysql('update ip_connect set Status=%d where IP="%s"'%(Status,record[i]))

還有一種方式與這個差不多,不過沒有返回值,直接打印出結果,即用系統命令os.system(cmd)

2、比這種快很多,適合服務器數量較大時使用,fping命令,它是對一個文件的批量ping,瞬間完成的,如果ping不通,那就較慢,日常ping不通的畢竟是少數,所以這個非常適用。來感受一下,它ping的結果,新建一個文件iplist,裡面是IP列表,fping結果如下:

其實結果就兩個 is alive / is unrreachable ,其它的中間檢測時它自己輸出的不用理會。

fping.sh :

#!/bin/bash
rm -f result.txt
cat ipmi_ping.txt | fping > result.txt

思路也很簡單,將IP列表讀取來寫進一個iplist文件,然後再對這個文件fping(調用fping.sh)批量執行的結果寫進result文件:

def check_online_ip():
ip = mysql('select * from ip_check')

#將IP寫進一個文件
if os.path.exists('iplist.txt'):
os.remove('iplist.txt')
iplist= 'iplist.txt'
for i in range(0,len(ip)):
with open(iplist, 'a') as f:
f.write(ip[i][0]+'\n')

#對文件中的IP進行fping
p = subprocess.Popen(r'./fping.sh',stdout=subprocess.PIPE)
p.stdout.read()

#讀result.txt文件,將IP is unreachable的行提取更新mysql狀態為1
result = open('result.txt','r')
content = result.read().split('\n')
for i in range(0,len(content)-1):
tmp = content[i]
ip = tmp[:tmp.index('is')-1]
Status = 0
if 'unreachable' in tmp:
Status = 1
#print i,ip
mysql('update ip_check set Status=%d where IP="%s"'%(Status,ip))
print 'check all ipconnectness over!'

將這個搞成計劃任務,每天跑幾遍,還是挺贊的。 呵呵。。

--------------------------------------分割線 --------------------------------------

CentOS上源碼安裝Python3.4 http://www.linuxidc.com/Linux/2015-01/111870.htm

《Python核心編程 第二版》.(Wesley J. Chun ).[高清PDF中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

《Python開發技術詳解》.( 周偉,宗傑).[高清PDF掃描版+隨書視頻+代碼] http://www.linuxidc.com/Linux/2013-11/92693.htm

Python腳本獲取Linux系統信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

在Ubuntu下用Python搭建桌面算法交易研究環境 http://www.linuxidc.com/Linux/2013-11/92534.htm

Python 語言的發展簡史 http://www.linuxidc.com/Linux/2014-09/107206.htm

Python 的詳細介紹:請點這裡
Python 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved