python檢測服務器是否ping通


好想在2014結束前再趕出個10篇博文來,~(>_<)~,不寫博客真不是一個好兆頭,至少說明對學習的欲望和對知識的研究都不是那么積極了,如果說這1天的時間我能趕出幾篇精致的博文,你們信不信,哈哈,反正我是信了。。。

 

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!'

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

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM