Python檢查ping終端的方法
菜鳥一枚,寫著試了試,雖說有點雜亂,但還是能用,我是在linux下運行的
大致說下過程:
1、把需要ping的網(wǎng)段中所有ip存到數(shù)組中(我是放到數(shù)組中了,其實直接for循環(huán),一個個的也行)
2、遍歷數(shù)組,逐個ping
3、根據(jù)ping返回的字符串,判斷是否ping通
4、結(jié)果存入txt中
下面上代碼咯(其實可以簡化代碼的,我這里就不簡化了)
#!/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)
就是一臺一臺的ping,判斷,有點慢!
以上這篇Python檢查ping終端的方法就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
- Pycharm中安裝wordcloud等庫失敗問題及終端通過pip安裝的Python庫如何添加到Pycharm解釋器中(推薦)
- Python在終端通過pip安裝好包以后在Pycharm中依然無法使用的問題(三種解決方案)
- Python終端輸出彩色字符方法詳解
- python paramiko遠程服務器終端操作過程解析
- 使用python模擬命令行終端的示例
- 在PyCharm的 Terminal(終端)切換Python版本的方法
- python隱藏終端執(zhí)行cmd命令的方法
- 淺談終端直接執(zhí)行py文件,不需要python命令
- 在Linux命令行終端中使用python的簡單方法(推薦)
- python如何在終端里面顯示一張圖片
- 用Python編寫一個基于終端的實現(xiàn)翻譯的腳本
- 在終端啟動Python時報錯的解決方案
相關(guān)文章
python 定時器,實現(xiàn)每天凌晨3點執(zhí)行的方法
今天小編就為大家分享一篇python 定時器,實現(xiàn)每天凌晨3點執(zhí)行的方法,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-02-02
pygame實現(xiàn)鍵盤的連續(xù)監(jiān)控
這篇文章主要為大家詳細介紹了pygame實現(xiàn)鍵盤的連續(xù)監(jiān)控,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-04-04
Pycharm中Python環(huán)境配置常見問題解析
這篇文章主要介紹了Pycharm中Python環(huán)境配置常見問題,結(jié)合圖文形式分析了Pycharm中Python環(huán)境配置模塊路徑問題、虛擬環(huán)境創(chuàng)建、配置遠程服務器、連接數(shù)據(jù)庫等常見問題與操作方法,需要的朋友可以參考下2020-01-01

