2016-08-13 644 views
-1

我在python中寫了一個簡單的概述,它的所有內容都只是互聯網的連接。 當他發現沒有連接時,他會將日誌文件寫入文本的小時和日期,然後退出程序。在Python腳本的循環中運行並記錄'ping'的輸出

我想要它繼續測試,如果有連接即使沒有,我該怎麼做?沒有程序退出

這是代碼:

import os 
import time 
def Main(): 

    ping =os.system('ping -n 1 -l 1000 8.8.8.8 ') 
    while ping ==0: 
     time.sleep(4) 
     ping = os.system('ping -n 1 -l 1000 8.8.8.8 ') 
     if ping ==1: 
      print 'no connection' 
      CT =time.strftime("%H:%M:%S %d/%m/%y") 
      alert=' No Connection' 
      f = open('logfile.txt','a+') 
      f.write('\n'+CT) 
      f.write(alert) 
      f.close() 



if __name__ == "__main__": 
    Main() 

感謝名單了很多。

+0

請注意,如果第一個'ping'命令失敗,'while'循環將不會運行。所以如果發生這種情況,什麼都不會寫入您的日誌文件。 –

回答

1

Main打電話給無限循環

if __name__ == "__main__": 
    while True: 
     Main() 
     time.sleep(1) # optional, as Main already contains a sleep time 
0

如果我理解正確你要跟這將做它的工作:

import os 
import time 

def Main(): 

    while True: 
     ping = os.system('ping -n 1 -l 1000 8.8.8.8 ') 
     if ping: 
      print 'no connection' 
      CT =time.strftime("%H:%M:%S %d/%m/%y") 
      alert=' No Connection' 
      with open('logfile.txt','a+') as f: 
       f.write('\n'+CT) 
       f.write(alert) 

     time.sleep(4) 

if __name__ == "__main__": 
    Main() 
+0

其未運行 – Xozu

+0

我省略了函數調用,修復了。 –

1

此代碼應設置你的方式。只需在調用LogPing對象時用您選擇的主機替換主機即可。

查看內嵌評論,並請問我是否有任何問題。

from datetime import datetime 
import os 
import shlex 
import subprocess 
from time import sleep 



class LogPing: 

    def __init__(self, host, count=1, timeout_seconds=10, logfile="ping_log.txt"): 
     self.host = host 
     self.count = count 
     self.timeout_seconds = timeout_seconds 
     self.logfile = logfile 

     self.output_blackhole = open(os.devnull, 'wb') 


    def _command(self): 
     command_string = "ping -c {count} -t {timeout} {host}".format(
       count=self.count, 
       timeout=self.timeout_seconds, 
       host=self.host 
      ) 

     try: 
      # we don't actually care about the output, just the return code, 
      # so trash the output. result == 0 on success 
      result = subprocess.check_call(
        shlex.split(command_string), 
        stdout=self.output_blackhole, 
        stderr=subprocess.STDOUT 
       ) 
     except subprocess.CalledProcessError: 
      # if here, that means that the host couldn't be reached for some reason. 
      result = -1 

     return result 

    def run(self): 
     ping_command_result = self._command() 

     if ping_command_result == 0: 
      status = "OK" 
     else: 
      status = "NOK" 

     # The time won't be exact, but close enough 
     message = "{status} : {time} : {host}\n".format(
       status=status, 
       time=datetime.utcnow().strftime("%Y-%m-%d_%T"), 
       host=self.host 
      ) 

     # open file in a context manager for writing, creating if not exists 
     # using a+ so that we append to the end of the last line. 
     with open(self.logfile, 'a+') as f: 
      f.write(message) 




if __name__ == "__main__": 
    while True: 
     ping_instance = LogPing("example.org").run() 
     sleep(4)