python循环监控远程端口的方法

yipeiwu_com6年前Python基础

本文实例讲述了python循环监控远程端口的方法。分享给大家供大家参考。具体如下:

在ip.txt中每行一个ip地址和端口号,代码可循环监控这些ip地址的指定端口是否正常

#!/usr/bin/env python
# -*- coding: gbk -*-
import socket,time
while 1:
  file_obj = open('ip.txt')
  for line in file_obj:
    try:
      sc=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
      ip = line.split()[0]
      port = int(line.split()[1])
      print ip,port
      #设置超时时间(0.0)
      sc.settimeout(2)
      sc.connect((ip,port))
      timenow=time.localtime()
      datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)
      logstr="%s:%s 连接成功->%s \n" %(ip,port,datenow)
      print logstr
      sc.close()
    except:
      file = open("log.txt", "a")
      timenow=time.localtime()
      datenow = time.strftime('%Y-%m-%d %H:%M:%S', timenow)
      logstr="%s:%s 连接失败->%s \n" %(ip,port,datenow)
      print logstr
      file.write(logstr)
      file.close()
  print "sleep 10....."
  time.sleep(10)

ip.txt格式文件:

192.168.1.100 33001
192.168.1.101 33001

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Python的argparse库使用详解

argparse是python标准库里面用来处理命令行参数的库 命令行参数分为位置参数和选项参数: 位置参数就是程序根据该参数出现的位置来确定的 如:[root@openstack...

pytorch查看torch.Tensor和model是否在CUDA上的实例

pytorch查看torch.Tensor和model是否在CUDA上的实例

今天训练faster R-CNN时,发现之前跑的很好的程序(是指在运行程序过程中,显卡利用率能够一直维持在70%以上),今天看的时候,显卡利用率很低,所以在想是不是我的训练数据torch...

Django 响应数据response的返回源码详解

响应数据的返回 在 WSGIHandler.__call__(self, environ, start_response) 方法调用了 WSGIHandler.get_response...

python远程调用rpc模块xmlrpclib的方法

RPC(Remote Procedure Call Protocol)是远程调用协议,它通过网络请求服务到远端服务器,服务器根据请求做出响应,将结果返回 它是一种C/S模式,客户端可以调...

Python学习笔记之常用函数及说明

基本定制型 复制代码 代码如下:C.__init__(self[, arg1, ...]) 构造器(带一些可选的参数)C.__new__(self[, arg1, ...]) 构造器(带...