<repo_name>SPuerBRead/Small-tools<file_sep>/SubDomainQuery.py
import argparse
import requests
import re

class SubDomainQuery():
	def __init__(self):
		UrlList = []

	def Query(self,url):
		data = {'domain':url,'b2':1,'b3':1,'b4':1}
		Queryre = requests.post('http://i.links.cn/subdomain/',data = data)
		file =  Queryre.text
		data = re.compile(r'<div class=domain><input type=hidden name=domain(.*?) id=domain(.*?) value="(.*?)"><input type=hidden name=domainlevel(.*?)  id=domainlevel')
		UrlList = re.findall(data,file)
		fopen = open(url+'.txt','w+')
		count = 0
		for i in UrlList:
			count+=1
			print "%s:\t%s" %(count,i[2])
			fopen.write(i[2]+'\n')
		fopen.close()

if  __name__ ==  '__main__':
	parse = argparse.ArgumentParser()
	parse.add_argument('-u',dest = 'url',help = 'Query url')
	args = parse.parse_args()
	url = args.url
	scan = SubDomainQuery()
	scan.Query(url)<file_sep>/PortScan.py
from __future__ import division
from itertools import product, islice
from os import linesep
import time
import argparse
import socket
import sys
import Queue
import threading


class Pscan():
    def __init__(self,start_ip,stop_ip,thread_num,ip,allscan):
        self.start_ip = start_ip
        self.stop_ip = stop_ip
        self.thread_num = thread_num
        self.IpQueue = Queue.Queue()
        self.Portlist = ['21','22','23','53','80','81','137','389','443','873','1090','1098','1099','1352','1433',
'1521','2049','2181','3306','3389','3700','4444','4445','4848','5000','5432','5632','5900','5901',
'5902','6379','7001','8020','8021','8080','8009','8069','8083','8093','9080','9081','9090','9200',
'9300','11211','27017','50070']
        self.mutex = threading.Lock()
        self.livelist = []
        self.singleIP = ip
        self.Detection = allscan
        self.PortQueue = Queue.Queue()
        self.iplist = []

    def get_ip(self,tofile='/tmp/ip_list.txt'):
        print 'Generating a dictionary ...'
        fmt="%s.%s.%s.%s"      #+linesep
        if int(self.start_ip.split('.')[0]) < int(self.stop_ip.split('.')[0]):
            p1 = xrange(int(self.start_ip.split('.')[0]),int(self.stop_ip.split('.')[0])+1)
            p2 = xrange(int(self.start_ip.split('.')[1]),256)
            p3 = xrange(int(self.start_ip.split('.')[2]),256)
            p4 = xrange(int(self.start_ip.split('.')[3]),256)
        elif int(self.start_ip.split('.')[1]) < int(self.stop_ip.split('.')[1]):
            p1 = xrange(int(self.start_ip.split('.')[0]),int(self.stop_ip.split('.')[0])+1)
            p2 = xrange(int(self.start_ip.split('.')[1]),int(self.stop_ip.split('.')[1])+1)
            p3 = xrange(int(self.start_ip.split('.')[2]),256)
            p4 = xrange(int(self.start_ip.split('.')[3]),256)
        elif int(self.start_ip.split('.')[2]) < int(self.stop_ip.split('.')[2]):
            p1 = xrange(int(self.start_ip.split('.')[0]),int(self.stop_ip.split('.')[0])+1)
            p2 = xrange(int(self.start_ip.split('.')[1]),int(self.stop_ip.split('.')[1])+1)
            p3 = xrange(int(self.start_ip.split('.')[2]),int(self.stop_ip.split('.')[2])+1)
            p4 = xrange(int(self.start_ip.split('.')[3]),256)
        elif int(self.start_ip.split('.')[3]) < int(self.stop_ip.split('.')[3]):
            p1 = xrange(int(self.start_ip.split('.')[0]),int(self.stop_ip.split('.')[0])+1)
            p2 = xrange(int(self.start_ip.split('.')[1]),int(self.stop_ip.split('.')[1])+1)
            p3 = xrange(int(self.start_ip.split('.')[2]),int(self.stop_ip.split('.')[2])+1)
            p4 = xrange(int(self.start_ip.split('.')[3]),int(self.stop_ip.split('.')[3])+1)
            #open(tofile,'w',256*1024).writelines(
        #    (fmt % tuple(i) for i in islice(product(p1,p2,p3,p4), None,None))
        #    )
        for i in islice(product(p1,p2,p3,p4), None,None):
            self.IpQueue.put(fmt % tuple(i))
            self.iplist.append(fmt % tuple(i))

    def listip_scan(self):
        thread = threading.current_thread()
        while(1):
            try:
                ip = self.IpQueue.get(timeout = 1)
            except:
                break
            for port in self.Portlist:
                self.mutex.acquire()
                sys.stderr.write('test: '+ ip +':'+ port+'       \r')
                self.mutex.release()
                host = (ip,int(port))
                sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
                sock.settimeout(0.3)
                try:
                    sock.connect(host)
                    self.mutex.acquire()
                    try:
                        data = sock.recv(1024)
                        sys.stderr.write('[+] '+ip+':'+port+'      open\t'+str(data).strip().encode('utf-8')+'\n')
                        self.livelist.append(ip+':'+port+':'+str(data).strip().encode('utf-8'))
                    except:
                        sys.stderr.write('[+] '+ip+':'+port+'      open\t\n')
                        self.livelist.append(ip+':'+port)
                    self.mutex.release()
                except:
                    pass
                sock.close()

    def StartThread(self,way):
        threadlist = []
        for i in range(int(self.thread_num)):
            T = threading.Thread(target = way)
            T.start()
            threadlist.append(T)
        for Th in threadlist:
            Th.join()
        return self.livelist

    def singleip_scan(self):
        while(1):
            try:
                port = self.PortQueue.get(timeout = 1)
            except:
                break
            self.mutex.acquire()
            sys.stderr.write('test: '+ self.singleIP +':'+ str(port)+'       \r')
            self.mutex.release()
            host = (self.singleIP,int(port))
            sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            sock.settimeout(0.3)
            try:
                sock.connect(host)
                self.mutex.acquire()
                try:
                    data = sock.recv(1024)
                    sys.stderr.write('[+] '+self.singleIP+':'+str(port)+'      open\t'+str(data).strip().encode('utf-8')+'\n')
                    self.livelist.append(ip+':'+port+':'+str(data).strip().encode('utf-8'))
                except:
                    sys.stderr.write('[+] '+self.singleIP+':'+str(port)+'      open\t\n')
                    self.livelist.append(self.singleIP+':'+str(port))
                self.mutex.release()
            except:
                pass
            sock.close()


    def run(self):
        relist = []
        if self.singleIP:
            self.iplist.append(self.singleIP)
            if self.Detection:
                for i in range(65536):
                    self.PortQueue.put(i)
            else:
                for i in self.Portlist:
                    self.PortQueue.put(i)
            relist = self.StartThread(self.singleip_scan)
        else:
            self.get_ip()
            relist = self.StartThread(self.listip_scan)
        return relist

    def WriteReport(self):
        filename = str(time.strftime("%Y-%m-%d-%H-%M-%S",time.localtime(time.time())))
        html = open('%s.html' %filename,'w')
        html.write("""
<html>
<head>
  <title>Report</title>
</head>
<body>
<h1 align="center">Pscan v1.0</h1>
<p style="text-align:right">2016.9.17 by <EMAIL></p>
<hr style="height:1px;border:none;border-top:1px dashed #0066CC;" />
""")
        for i in self.iplist:
            flag = 0
            for j in self.livelist:
                if j.split(':')[0] == i:
                    if flag == 0:
                        html.write('<h2>%s</h2>' %j.split(':')[0])
                        html.write('<hr style="height:1px;border:none;border-top:1px dashed #0066CC;" />')
                        flag = 1
                    if len(j.split(':'))>2:
                        html.write(r'<li><a href="http://%s">%s</a>%s</li>' %(j.split(':')[0]+':'+j.split(':')[1],j.split(':')[0]+':'+j.split(':')[1],'    '+j.split(':')[2]))
                    else:
                        html.write(r'<li><a href="http://%s">%s</a></li>' %(j,j))
        html.write('</body></html>')
        html.close()




def main(start_ip,stop_ip,thread_num,ip,allscan):
    relist = []
    scan = Pscan(start_ip,stop_ip,thread_num,ip,allscan)
    relist = scan.run()
    scan.WriteReport()



if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    eg = '''
Usage: python PPscan.py --start 1.1.1.1 --stop 2.2.2.2 [-t]
        or
       python PPscan.py -i 1.1.1.1 [-a] [-t]
    '''
    parser.add_argument('--start',dest = 'start_ip',help = 'Start IP')
    parser.add_argument('--stop',dest = 'stop_ip',help = 'Stop IP')
    parser.add_argument('-t',dest = 'thread_num',type = int,default = 1,help = 'thread num')
    parser.add_argument('-i',dest = 'ip',help = 'single ip scan')
    parser.add_argument('-a',dest = 'all',action = 'store_true',default = False,help = 'scan all port')
    args = parser.parse_args()
    start_ip = args.start_ip
    stop_ip = args.stop_ip
    thread_num = args.thread_num
    ip = args.ip
    allscan = args.all
    if start_ip == None and ip == None:
        print eg
    else:
        start = time.time()
        main(start_ip,stop_ip,thread_num,ip,allscan)
        end = time.time()
        print '\nruntime: '+str(end - start)
