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

相关文章

python好玩的项目—色情图片识别代码分享

python好玩的项目—色情图片识别代码分享

一、实验简介 本实验将使用 Python3 去识别图片是否为色情图片,我们会使用到 PIL 这个图像处理库,会编写算法来划分图像的皮肤区域 1.1. 知识点 Python 3 的模块的安...

Python的ORM框架中SQLAlchemy库的查询操作的教程

1. 返回列表和标量(Scalar) 前面我们注意到Query对象可以返回可迭代的值(iterator value),然后我们可以通过for in来查询。不过Query对象的all()、...

python 对给定可迭代集合统计出现频率,并排序的方法

给定一个可迭代sequence,对其中的值进行出现次数统计: 方法1: def get_counts(sequence): counts = {} for x in sequen...

Python Sphinx使用实例及问题解决

这篇文章主要介绍了Python Sphinx使用实例及问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 描述 使用 pip 安...

使用url_helper简化Python中Django框架的url配置教程

django的url采用正则表达式进行配置,虽然强大却也广为诟病。反对者们认为django的url配置过于繁琐,且不支持默认的路由功能。 我倒觉得还好,只是如果觉得不爽,为什么不自己小小...