阿里云-云小站(无限量代金券发放中)
【腾讯云】云服务器、云数据库、COS、CDN、短信等热卖云产品特惠抢购

Python批量扫描服务器80端口状态

122次阅读
没有评论

共计 2027 个字符,预计需要花费 6 分钟才能阅读完成。

用 Python 写了一个简陋的端口扫描脚本,其简单的逻辑如下:

1. python DetectHostPort.py iplist.txt(存放着需要扫描的 IP 地址列表的文本,每行一个地址)

2. 输入扫描端口、扫描时间和扫描间隔。

3. 输出扫描信息。

下面贴上源码,欢迎拍砖。

#!/usr/bin/env python

import sys
import time
import socket


def getaddresslist(addr):
    """
    getaddresslist(addr) -> IP address file

    IP address read from the file.
    :param addr: IP file
    :return: Scan ip address list, or error message.
    """
    address = []
    try:
        with open(addr, "r") as iplist:
            line = iplist.readlines()
            for item in line:
                address.append(item.strip("\n"))
        return address

    except (IOError, IndexError), e:
        return str(e)


def scan(iplist, port=80):
    """
    scan() -> getaddresslist()

    getaddresslist() function returns the IP address of the list.
    :param iplist: getaddresslist() Function return value.
    :param port: Need to scan the port.
    :return: None
    """
    if not isinstance(iplist, list):
        sys.exit("Function getaddresslist() return error message: %s" % iplist)
    # start_time = time.time()

    for addr in iplist:
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(1)
        host = (addr, int(port))
        try:
            s.connect(host)
            print "Host %s:%s connection success." % (host[0], host[1])
        except Exception, e:
            print "Host %s:%s connection failure: %s" % (host[0], host[1], e)

        s.close()


if __name__ == '__main__':

    addrs = sys.argv[1]
    ScanPort = input("Enter the scan port: ")
    Total = input("Enter the scan time <minutes>: ")
    Interval = input("Enter the scanning interval <minutes>: ")
EndTime
= time.time() + Total * 60 while time.time() < EndTime: scan(getaddresslist(addrs), ScanPort) time.sleep(Interval * 60) continue else: print "\nwhile end."

运行时只能扫描一个端口,但是可以对代码进行修改,扩展为扫描多个端口。

 

Ubuntu 14.04 安装 Python 3.3.5  http://www.linuxidc.com/Linux/2014-05/101481.htm

 

CentOS 上源码安装 Python3.4  http://www.linuxidc.com/Linux/2015-01/111870.htm

 

《Python 核心编程 第二版》.(Wesley J. Chun).[高清 PDF 中文版] http://www.linuxidc.com/Linux/2013-06/85425.htm

 

《Python 开发技术详解》.(周伟, 宗杰).[高清 PDF 扫描版 + 随书视频 + 代码] http://www.linuxidc.com/Linux/2013-11/92693.htm

 

Python 脚本获取 Linux 系统信息 http://www.linuxidc.com/Linux/2013-08/88531.htm

 

在 Ubuntu 下用 Python 搭建桌面算法交易研究环境 http://www.linuxidc.com/Linux/2013-11/92534.htm

 

Python 语言的发展简史 http://www.linuxidc.com/Linux/2014-09/107206.htm

 

Python 的详细介绍 :请点这里
Python 的下载地址 :请点这里

本文永久更新链接地址 :http://www.linuxidc.com/Linux/2016-09/135621.htm

 

正文完
星哥说事-微信公众号
post-qrcode
 
星锅
版权声明:本站原创文章,由 星锅 2022-01-21发表,共计2027字。
转载说明:除特殊说明外本站文章皆由CC-4.0协议发布,转载请注明出处。
【腾讯云】推广者专属福利,新客户无门槛领取总价值高达2860元代金券,每种代金券限量500张,先到先得。
阿里云-最新活动爆款每日限量供应
评论(没有评论)
验证码
【腾讯云】云服务器、云数据库、COS、CDN、短信等云产品特惠热卖中