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

WBOY
Release: 2016-06-06 11:22:42
Original
1701 people have browsed it

本文实例讲述了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)
Copy after login

ip.txt格式文件:

192.168.1.100 33001
192.168.1.101 33001
Copy after login

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

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!