python检测主机的连通性并记录到文件的实例

yipeiwu_com6年前Python基础

目录结构

ping_test/
├── bin
│ ├── ping.py
│ ├── ping_run.sh.origin
│ └── ping.sh
├── conf
│ └── ip.lst
├── logs
│ ├── 10.10.37.196_2017-06-28_ping.log
│ └── 10.10.62.229_2017-06-28_ping.log
└── README.md

代码

cat bin/ping.py

#!/usr/bin/env python
#-*- coding: utf-8

from subprocess import Popen, PIPE
import shlex
import time
import datetime
import sys, os

basedir = os.path.dirname( os.path.dirname( os.path.abspath(__file__) ) )
cnf = os.path.join( basedir, 'conf', 'ip.lst' )
# print cnf

while True:
 today = datetime.datetime.strftime( datetime.datetime.now(), "%Y-%m-%d" )
 with open(cnf) as f:
  for host in f:
   host = host.strip()
   cmd = 'sh ping.sh %s' % host
   args = shlex.split(cmd)
   p = Popen(args, stdout=PIPE, stderr=PIPE)
   stdout, stderr = p.communicate()

   filename = host + '_%s_ping.log' % today
   logfile = os.path.join(basedir, 'logs', filename)
   # print logfile

   if stdout:
    with open(logfile, 'ab') as fd:
     fd.write( stdout )
     fd.flush()
   elif stderr:
    print('ping lost')
 time.sleep(1)

cat ping.sh

#!/bin/bash

HOST=$1
ping -c 1 ${HOST} | grep 'bytes from' | awk '{print $0"\t" strftime("%T %F", systime())}'

以上这篇python检测主机的连通性并记录到文件的实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Scrapy使用的基本流程与实例讲解

Scrapy使用的基本流程与实例讲解

前面已经介绍过如何创建scrapy的项目,和对项目中的文件功能的基本介绍。 这次,就来谈谈使用的基本流程: (1)首先第一点,打开终端,找到自己想要把scrapy工程创建的路径。这里,我...

Python2.7 实现引入自己写的类方法

系统环境:win10 开发环境:JetBrains PyCharm 2017.1.5 x64 Python版本:2.7 假如我们有一个class叫DBUtil,它在A.py里(最好一...

Python基于hashlib模块的文件MD5一致性加密验证示例

本文实例讲述了Python基于hashlib模块的文件MD5一致性加密验证。分享给大家供大家参考,具体如下: 使用hashlib模块,可对文件MD5一致性加密验证: #python...

Python方法的延迟加载的示例代码

数据挖掘的过程中,数据进行处理是一重要的环节,我们往往会将其封装成一个方法,而有的时候这一个方法可能会被反复调用,每一次都对数据进行处理这将是一个很耗时耗资源的操纵,那么有没有办法将计算...

python之pyqt5通过按钮改变Label的背景颜色方法

python之pyqt5通过按钮改变Label的背景颜色方法

使用setStyleSheet方法修改得到自己想要的字体,大小,颜色 self.lab = QLabel("标签字体大小颜色", self) self.lab.setGeometry...