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

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

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

2. 输入指定的扫描端口,扫描后完成后将生成日志文件。

 

源码如下:

#!/usr/bin/env python

import sys
import time
import socket


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

    IP address read from the file.
    """
    try:
        with open(addr, "r") as ip_list:
            lines = ip_list.readlines()
            address = [line.strip() for line in lines]
        return address
    except (IOError, IndexError), e:
        return str(e)


def scan(ip_list, port):
    """
    scan() -> getaddresslist()

    getaddresslist() function returns the IP address of the list.
    """
    if not isinstance(ip_list, list):
        sys.exit("Function getaddresslist() return error message: %s" % ip_list)

    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    s.settimeout(1)
    f = open('E:\programming\public\python\scan.log', 'ab')
    for addr in ip_list:
        host = (addr, int(port))
        try:
            s.connect(host)
            f.write("Host %s:%s connection success. \n" % (host[0], host[1]))
        except Exception, e:
            f.write("Host %s:%s connection failure: %s. \n" % (host[0], host[1], e))
    f.close()
    s.close()
    return True


if __name__ == '__main__':

    addrs = sys.argv[1]
    isNone = True
    while isNone:
        scanport = raw_input("Enter the scan port: ")
        if scanport:
            isNone = False
        else:
            continue
    scan(getaddresslist(addrs), scanport)

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

转载于:https://www.cnblogs.com/XuHoo/p/5888528.html

你可能感兴趣的:(Python批量扫描服务器指定端口状态)