标签:type 端口扫描器 com block time rgs finally ethos send
一个用python写的简单的端口扫描器,python环境为 3.7.0,windows系统
扫描给定主机是否开放了指定的端口
TCP连接扫描是利用TCP的三次握手来确定主机的端口是否开放。确定主机端口开放之后,给端口发送消息,接收端口返回的消息,然后判断该端口运行的服务。
使用时,-H?参数可以提供主机的域名或者ip地址,-p/-P?写要扫描的端口,多个端口用逗号分隔
‘‘‘
@Author:yw
参考书籍:《python绝技:运用python成为顶级***》
‘‘‘
import optparse
from socket import *
import threading
threadlock = threading.Lock() #实例化threadlock对象
def Conn_scan(Host, Port):
try:
conn = socket(AF_INET,SOCK_STREAM)
conn.connect((Host, Port))
#conn.send(‘ywboy‘.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(‘[-]%d/Tcp Closed‘ % Port)
finally:
threadlock.release()
conn.close()
def Port_scan(Host, Ports):
try:
IP = gethostbyname(Host) ##获得对应主机的ip地址
except:
print("[-] Cannot resolve ‘%s‘:Unknow host" % Host)
return
try:
Name = gethostbyaddr(Host) ##获得对应主机的信息,返回主机名、主机别名列表、主机IP地址列表
print("\n[+] Scan result for:"+Name[0])
except:
print("\n[+] Scan Results for:"+IP)
setdefaulttimeout(1)
for Port in Ports:
print("Scan port:"+Port)
Conn_scan(Host, int(Port))
def main():
usage = "usage %prog -H <target Host> -p/-P <target ports>"
parse = optparse.OptionParser(usage)
parse.add_option(‘-H‘, dest=‘Host‘, type=‘string‘, help=‘target Host‘)
parse.add_option(‘-p‘,‘-P‘, dest=‘Ports‘, type=‘string‘, help=‘SCan Port‘)
(options, args) = parse.parse_args()
Host = options.Host
Ports = str(options.Ports).split(‘,‘)
if (Host==None)|(Ports==None):
print(parse.usage)
exit(0)
Port_scan(Host,Ports)
if __name__ == ‘__main__‘:
main()
上述代码,因为我只是做了端口扫描,所以注释掉的判断端口扫描服务的代码
标签:type 端口扫描器 com block time rgs finally ethos send
原文地址:https://blog.51cto.com/14113984/2438006