码迷,mamicode.com
首页 > 其他好文 > 详细

端口扫描器

时间:2019-03-25 01:10:13      阅读:176      评论:0      收藏:0      [点我收藏+]

标签:sem   获取   nec   timeout   screen   线程   scanning   eth   soc   

#!/usr/bin/env python
# -*- coding:UTF-8 -*-
import optparse
import socket
import threading

# 用法 python threadPortScan.py -H www.baidu.com -p 22 23 3306 3389 6437 445 443 7001 80
#构造一个方法  创建具有给定许可数的计数信号量并设置为非公平信号量,就是说创建一个阻塞对象
screenLock = threading.Semaphore(value=1)
def connScan(tgtHost,tgtPort):
    try:
        #创建一个套接字对象
        connSkt = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        #尝试连接
        connSkt.connect((tgtHost,tgtPort))
        #发送数据
        connSkt.send("violent pyhon\r\n")
        #接受饭回来的数据
        result = connSkt.recv(100)
        #产生的线程排好队,一个一个得打印
        screenLock.acquire()
        print "[+]%d/tcp open" %tgtPort
        print "[+]" + str(result)
    except:
        print "[-]%d/tcp closed" %tgtPort
    finally:
        #释放掉
        screenLock.release()
        #关闭连接
        connSkt.close()
        
def portScan(tgtHost,tgtPorts):
    try:
        #根据域名,获取ip
        tgtIP = socket.gethostbyname(tgtHost)
    except:
        print "[-]cannot resolve ‘%s‘:Unkonwn host" %tgtHost
        return
    try:
        tgtName = socket.gethostbyaddr(tgtIP)
        print "\n[+]Scan Result for:" + tgtName[0]
    except:
        print "\n[+]Scan Result for:" + tgtIP
    socket.setdefaulttimeout(1)
    for tgtPort in tgtPorts:
        print "Scanning port " + str(tgtPort)
        t = threading.Thread(target = connScan,args = (tgtHost,int(tgtPort)))
        t.start()

def main():
    parse = optparse.OptionParser(usage %prog -H <targethost> -p <targetport>)
    parse.add_option(-H,dest = tgtHost,type = string,help = specify target host)
    parse.add_option(-p,dest = tgtPort,type = int,help = specify target port)
    (option,args) = parse.parse_args()
    tgtHost = option.tgtHost
    tgtPort = option.tgtPort
    args.append(tgtPort)
    if(tgtPort == None) | (tgtHost == None):
        print parse.usage
        exit(0)
    portScan(tgtHost,args)

if __name__ == __main__:
    main()

 

端口扫描器

标签:sem   获取   nec   timeout   screen   线程   scanning   eth   soc   

原文地址:https://www.cnblogs.com/kunspace/p/10591474.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!