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程序设计有所帮助。

相关文章

Tornado协程在python2.7如何返回值(实现方法)

错误写法 class RemoteHandler(web.RequestHandler): @gen.coroutine def get(self): resp...

python读取和保存图片5种方法对比

python读取和保存图片5种方法对比 python中对象之间的赋值是按引用传递的,如果需要拷贝对象,需要用到标准库中的copy模块 方法一:利用 PIL 中的 Image 函数 这个函...

使用pip发布Python程序的方法步骤

使用pip发布Python程序的方法步骤

写过 Python 程序的小伙伴们都知道,需要 import 个非 Python 自带的软件包时,都要用到 pip 这个程序。平时我们都是用 pip,如果我们写好了一个程序,想让大家都能...

wxpython 学习笔记 第一天

它是Python语言对流行的wxWidgets跨平台GUI工具库的绑定。而wxWidgets是用C++语言写成的。   和Python语言与wxWidgets GUI工具库一样,wxPy...

Python中的取模运算方法

Python中的取模运算方法

所谓取模运算,就是计算两个数相除之后的余数,符号是%。如a % b就是计算a除以b的余数。用数学语言来描述,就是如果存在整数n和m,其中0 <= m < b,使得a = n...