利用Python编写一个TCP端口的扫描器
要求
输入一个主机号和端口列表,并扫描发送数据并获取Banner信息
知识掌握
optparse模块
- 简介
optparse用于处理命令行参数 - 基本用法
import optparse
parser = OptionParser(usage) # 实例化一个,可以带参,也可以不带参数,带参的话会把参数变量的内容作为帮助信息输出
parser.add_option('-f', '--file',action='store', default='test', dest='filename' ,help='help text)
# 通过add_option来增加参数配置,格式parser.add_option(短参名,长参名, dest='', action='',help='', default='', type='')
(options, args) = parser.parse_args() #parse_args可以有参数,不定义的话使用默认的sys.argv[1:]
socket编程
掌握下面两种
- 服务端
#! /usr/bin/python3.8
# coding:utf-8
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 创建一个socket对象IPV4 TCP
host = "127.0.0.1"
port = 4444
s.bind((host,port)) # 将端口和ip绑定
s.listen(5) # 开始监听,最多允许5个主机连接
print("Listening...")
conn, addr = s.accept() # 建立客户端连接,conn是一个实例
print("Connected by %s" % str(addr))
data = conn.recv(1024) # 表示接收1024比特数据
conn.send('Hello!'.encode('utf-8')) # 发送数据给客户端
conn.close() # 关闭实例
s.close() # 关闭连接
- 客户端
#! usr/bin/python3.8
# coding:utf-8
import socket
host = '192.168.95.243'
port = 9999
c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect((host, port)) # 主动初始化TCP服务器连接
sdata = "Welcome!"
c.send(sdata.encode('utf-8'))
data = c.recv(1024)
print(data)
c.close()
Threading模块
- 简介
包含了关于线程操作的丰富功能 - 多进程基本使用
import threading
t = threading.Thread(target=func1,args=(1,2))
t.start()
screenLock = threading.Semaphore(value=1) # 创建一个信号量对象
screenLock.acquire()# 计数器减一
screenLock.release()# 计数器加一,如果为0则阻塞当前进程
最终脚本
#! /usr/bin/python3.8
# -*- coding:utf-8 -*-
import optparse
import sys
import socket
import threading
screenLock = threading.Semaphore(value=1)
def connScan(tgthost, tgtport):
try:
c = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
c.connect((tgthost, tgtport))
c.send("Hello, friend\r\n".encode('utf-8'))
results = c.recv(1024)
screenLock.acquire()
print("[+]%d/tcp open" % tgtport)
print("[+]" + str(results))
except:
screenLock.acquire()
print("[-]%d/tcp closed" % tgtport)
finally:
screenLock.release()
c.close()
def portScan(tgthost, tgtports):
try:
tgtIP = socket.gethostbyname(tgthost)
except:
print("[-] Unknown host")
return
try:
tgtName = socket.gethostbyaddr(tgtIP)
print("[+] Scan Results for: " + tgtName[0])
except:
print("[+] Scan Results for: " + tgtIP)
socket.setdefaulttimeout(3)
for tgtport in tgtports:
print("Scanning port " + tgtport)
t = threading.Thread(target=connScan,args=(tgthost,int(tgtport)))
t.start()
def main():
usage = 'usage %prog'+' -t <target host> -p <target port>'
parser = optparse.OptionParser(usage=usage)
parser.add_option('-t','--target',dest='tgthost',type='string',help='specify target host')
parser.add_option('-p','--port',dest='tgtport',type='string',help='specify target port')
(options, args) = parser.parse_args()
tgthost = options.tgthost
tgtports = str(options.tgtport).split(',')
if (tgthost == None) | (tgtports == None):
print("You must specify at least a target host and port[s]")
print(usage)
sys.exit(0)
portScan(tgthost, tgtports)
if __name__=="__main__":
main()
效果如下