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

yipeiwu_com5年前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设计】。

相关文章

Python语言检测模块langid和langdetect的使用实例

之前使用数据编码风格检测的模块chardet比较多一点,今天提到的两个模块是检测数据的语言类型,比如是:中文还是英文,模块的使用方法也比较简单,我这里只是简单地使用了一下,因为项目中有这...

python OpenCV学习笔记实现二维直方图

python OpenCV学习笔记实现二维直方图

本文介绍了python OpenCV学习笔记实现二维直方图,分享给大家,具体如下: 官方文档 – https://docs.opencv.org/3.4.0/dd/d0d/tutori...

Python urllib模块urlopen()与urlretrieve()详解

1.urlopen()方法urllib.urlopen(url[, data[, proxies]]) :创建一个表示远程url的类文件对象,然后像本地文件一样操作这个类文件对象来获取远...

python实现逐个读取txt字符并修改

python实现逐个读取txt字符并修改

最近写毕业设计遇到一个问题,就是我从一个txt文件中逐个读取字符,并修改其中的内容后存到另一个txt文件中,如下图: 字符替换规则是把所有的0转化为1,把所有的255转化为0。当然程序...

Python退火算法在高次方程的应用

Python退火算法在高次方程的应用

一,简介 退火算法不言而喻,就是钢铁在淬炼过程中失温而成稳定态时的过程,热力学上温度(内能)越高原子态越不稳定,而温度有一个向低温区辐射降温的物理过程,当物质内能不再降低时候该物质原子态...