直接上代码
testXXXX.py:
import loggingimport logging.handlersimport subprocessimport timeclass CliTool: def __init__(self): pass def cmd_sync(self, cmdlist): res = subprocess.run(cmdlist, capture_output=True, check=True) return res def cmd_async_nowait(self, cmd): p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) out, err = p.communicate() return out, err def cmd_async_wait(self, cmd, timeout): p = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE) time_out_flag = False for i in range(timeout): time.sleep(1) if None == p.poll(): # subprocess is in progress. if i + 1 >= timeout: p.kill() time_out_flag = True break else: continue else: break if time_out_flag: out = [] err = ['timeout'] else: out, err = p.communicate() return out, errclass testXXXX: def __init__(self): self.logger = logging.getLogger('testXXXX') self.configLog() self.cli_tool = CliTool() def configLog(self): self.logger = logging.getLogger('testXXXX') self.logger.setLevel(level=logging.INFO) # timestamp format same with syslog timestamp format formatter = logging.Formatter('%(asctime)s - [%(filename)s:%(lineno)d] - %(message)s', "%b %d %H:%M:%S") file_handler = logging.handlers.WatchedFileHandler('/var/log/mylog') file_handler.setLevel(level=logging.INFO) file_handler.setFormatter(formatter) self.logger.addHandler(file_handler) def doTest(self): while True: out, err = self.cli_tool.cmd_async_wait('ping www.baidu.com -c 10', 60) outputList = str(out).split('\n') for line in outputList: self.logger.info(line)if __name__ == '__main__': testObj = testXXXX() testObj.doTest()
testXXXX_config.sh
#!/bin/bashmv testXXXX.service /lib/systemd/system/mv testXXXX.py /usr/bin/ln -s /lib/systemd/system/testXXXX.service /etc/systemd/system/systemctl enable /etc/systemd/system/testXXXX.service
test_XXXX.service
[Unit]Description=test XXXXAfter=YYYY.service[Service]Type=simpleRestart=alwaysRestartSec=10ExecStart=/usr/bin/python3 /usr/bin/test_XXXX.py[Install]WantedBy=multi-user.target