共计 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
