Python 检测IP与port

 

#!/usr/bin/env python
##
##check host and ports are UP or DOWN!
##read source file format :
##ip port port port ....
##

import os,sys,re
import subprocess
import socket

def runCheck(line):
    if(line == ""): 
        return

    ip_ports = line.split( )
    ip = ip_ports[0]

    p = subprocess.Popen(["ping -c 2 "+ ip],
                            stdin = subprocess.PIPE,
                            stdout = subprocess.PIPE,
                            stderr = subprocess.PIPE,
                            shell = True)
    out = p.stdout.read()
    regex = re.compile("time=\d*", re.IGNORECASE | re.MULTILINE)
    if len(regex.findall(out)) > 0:
        print "Server " + ip + " UP!"

        for port in ip_ports[1:]:
        sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sk.settimeout(1)
            try:
                sk.connect((ip,int(port)))
                print "Server " + ip + " port " + port + " OK!"
            except Exception, e:
                print "ERROR: Server " + ip + " port " + port + " not connect! " + repr(e)
            sk.close()    
    else:
        print "ERROR: Server " + ip + " DOWN!"



source = "ips.lst"    
if os.path.exists(source):
    
    file_obj = open("ips.lst")
    for line in file_obj.readlines():
        runCheck(line.strip())

    exit()
else:
    print "ERROR: source file is not exist;"
vim ips.lst
192.168.1.4 22 80
192.168.1.5 80
192.168.1.20
result:
Server 192.168.1.4 UP!
Server 192.168.1.4 port 22 OK!
Server 192.168.1.4 port 80 OK!
ERROR: Server 192.168.1.5 DOWN!
Server 192.168.1.20 UP!

 

posted on 2017-06-21 16:23  西风古道 阅读( ...) 评论( ...) 编辑 收藏

转载于:https://www.cnblogs.com/g120992880/p/7060204.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值