一个用python写的简单的端口扫描器,python环境为 3.7.0,windows系统
TCP连接扫描是利用TCP的三次握手来确定主机的端口是否开放。确定主机端口开放之后,给端口发送消息,接收端口返回的消息,看该端口运行的服务。
使用时,-H 参数可以提供主机的域名或者ip地址,-p/-P 写要扫描的端口,多个端口用逗号分隔
# -*- coding: utf-8 -*-
"""
Created on Sat Nov 3 16:44:28 2018
@author: 小谢
"""
import optparse
from socket import *
import threading
threadLock=threading.Lock() #实例化threadLock对象
def connScan(Host,Port):
try:
conn=socket(AF_INET,SOCK_STREAM)
conn.connect((Host,Port))
conn.send('test message'.encode("utf-8")) #发送测试信息给端口
results=conn.recv(100) #接收主机返回的信息
threadLock.acquire() #加锁
print('[+]%d/tcp open'% Port)
print('[+] '+results.decode("utf-8"))
conn.close()
except Exception as e:
threadLock.acquire()
print(e)
print('[-]%d/tcp closed'% Port)
finally:
threadLock.release() #释放锁
conn.close()
def portScan(Host,Ports):
try:
IP=gethostbyname(Host) ##获得对应主机的ip地址
except:
print("[-] Cannot resolve '%s':Unknown host" %Host)
return
try:
Name=gethostbyaddr(Host) ##获得ip对应主机的信息
print ("\n[+] Scan Results for:"+Name[0])
except:
print ("\n[+] Scan Results for:"+IP)
setdefaulttimeout(1)
for Port in Ports:
print ("Scanning port "+Port)
connScan(Host,int(Port))
def main():
usage="usage %prog -H <target host> -p/-P <target ports>"
parser=optparse.OptionParser(usage) #创建对象实例
parser.add_option('-H',dest='Host',type='string',help='target host') ##需要的命令行参数
parser.add_option('-P','-p',dest='Ports',type='string',help='target ports')
(options,args)=parser.parse_args()
Host=options.Host
Ports=str(options.Ports).split(',')
if (Host==None)|(Ports==None): ##如果主机和端口都是空的话
print(parser.usage)
exit(0)
portScan(Host,Ports)
if __name__=='__main__':
main()
相关知识点:Python中的optparse模块的使用