Python中怎么對(duì)ping終端進(jìn)行檢查,很多新手對(duì)此不是很清楚,為了幫助大家解決這個(gè)難題,下面小編將為大家詳細(xì)講解,有這方面需求的人可以來學(xué)習(xí)下,希望你能有所收獲。

過程:
1、把需要ping的網(wǎng)段中所有ip存到數(shù)組中(我是放到數(shù)組中了,其實(shí)直接for循環(huán),一個(gè)個(gè)的也行)
2、遍歷數(shù)組,逐個(gè)ping
3、根據(jù)ping返回的字符串,判斷是否ping通
4、結(jié)果存入txt中
下面上代碼咯(其實(shí)可以簡化代碼的,我這里就不簡化了)
#!/usr/bin/env python
# coding: utf8
import time
import subprocess
import codecs
import os
import re
# telnet host
def pingComputer(host, statusFile):
status1 = 'ping success'
status2 = 'ping faild'
errorStr = 'Destination'
for ipAdd in host:
print ("get: " +ipAdd + " status")
# get now time
nowTime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))
p = os.popen("ping -q -c 2 -r " + ipAdd)
line = p.read()
# judge errorstr in line if
if errorStr in line:
writeToText(nowTime, ipAdd, status2, statusFile)
else:
writeToText(nowTime, ipAdd, status1, statusFile)
# write status information to txt
def writeToText(nowTime, ipAdd, status, statusFile):
s_text = 'TIME:' + nowTime + '\t' + 'IP:' + ipAdd + '\t' + 'STATUS:' + status + '\r\n'
if '0' == judgeFile(statusFile):
with open(statusFile, 'a') as f:
f.write(s_text)
f.close()
if '1' == judgeFile(statusFile):
with open(statusFile, 'w') as f:
f.write(s_text)
f.close()
# Determine whether statusFile exists
# 0: exists
# 1: no exists
def judgeFile(statusFile):
if os.path.exists(statusFile):
return '0'
else:
return '1'
if __name__ == "__main__":
IpFirst = '192.168.1.'
# ip:1~254
host = []
for j in range(254):
host.append(IpFirst + str(j + 1))
# write file
statusFile = '/root/UpStatus.txt'
pingComputer(host, statusFile)看完上述內(nèi)容是否對(duì)您有幫助呢?如果還想對(duì)相關(guān)知識(shí)有進(jìn)一步的了解或閱讀更多相關(guān)文章,請關(guān)注創(chuàng)新互聯(lián)行業(yè)資訊頻道,感謝您對(duì)創(chuàng)新互聯(lián)的支持。
網(wǎng)站名稱:Python中怎么對(duì)ping終端進(jìn)行檢查-創(chuàng)新互聯(lián)
標(biāo)題URL:http://www.yijiale78.com/article44/cessee.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供定制網(wǎng)站、動(dòng)態(tài)網(wǎng)站、定制開發(fā)、域名注冊、服務(wù)器托管、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容