scan camera

getIPListByIPMask.py
#coding=utf-8
#http://ipblock.chacuo.net/down/t_txt=c_CN
from multiprocessing.dummy import Pool as ThreadPool
import re,datetime
# 生成下一次循环的边界条件

def ip2num(ip):
    ip=[int(x) for x in ip.split('.')]
    return ip[0] <<24 | ip[1]<<16 | ip[2]<<8 |ip[3]
def num2ip(num):
    return '%s.%s.%s.%s' %( (num & 0xff000000) >>24,
                            (num & 0x00ff0000) >>16,
                            (num & 0x0000ff00) >>8,
                            num & 0x000000ff )
def get_ip(ip):
    start,end = [ip2num(x) for x in ip.split('-') ]
    return [ num2ip(num) for num in range(start,end+1) if num & 0xff ]

def gen_ip(ip_range):
    iplist = get_ip(ip_range)
    filename = re.sub(r'[^0-9]', '',str(datetime.datetime.now())) + '.txt'
    with open(filename, "a+") as wObej:
        for ip in iplist:
            print (ip)
            wObej.write(ip + "\n")
    wObej.close()

if __name__ == '__main__':
    ip_ranges=[]
    with open("zh_IP.txt", "r") as f:
        for line in f.readlines():
            lineList = line.split("\t")
            iP_mask = lineList[0] + "-" + lineList[1]
            ip_ranges.append(iP_mask)
    f.close
    print("strart gen ip")
    pool = ThreadPool(processes=4)
    results = pool.map(gen_ip, ip_ranges)
    pool.close()
    pool.join()
554Scan.py
# coding: utf-8

import socket
from datetime import datetime
from multiprocessing.dummy import Pool as ThreadPool

def scan_port(ip,port=554):
    try:
        s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        s.settimeout(5)
        remote_server_ip = socket.gethostbyname(ip)

        print '-' * 60
        print 'Please wait, scanning remote host %s port %s'%( remote_server_ip,port)
        print '-' * 60
        res = s.connect_ex((remote_server_ip,port))
        if res == 0: # 如果端口开启 发送 hello 获取banner
            with open("554IP.txt","a+") as f :
                f.write(ip+"\n")
                f.close()
            try:
                s.send('hello')
                banner = s.recv(1024)


            except Exception,e:
                print 'Port {}: OPEN'.format(port)
                print str(e.message)
            else:
                print 'Port {}: OPEN'.format(port)
                print 'Banner {}'.format(banner)

        s.close()
    except Exception,e:
        print str(e.message)



# Check what time the scan started
t1 = datetime.now()


pool = ThreadPool(processes = 2)
ipList=[]
with open("netwave.txt","r") as f:
    for line in f.readlines():
        ipList.append(line.strip("\n"))
print("*test ip %d num "%len(ipList))
results = pool.map(scan_port,ipList)
pool.close()
pool.join()

print 'Multiprocess Scanning Completed in  ', datetime.now() - t1
scan_camera.py
#coding=utf-8

#http://86.254.95.226:81/get_status.cgi  判断摄像头
#/get_camera_params.cgi
#/snapshot.cgi
#/videostream.cgi

# coding: utf-8

import requests
from datetime import datetime
from multiprocessing.dummy import Pool as ThreadPool
import socket
import re



def check_webserver(address, port):

        request_string = "GET / HTTP/1.1\r\nHost: %s\r\n\r\n" %address
        # print 'HTTP request:'
        # print '|||%s|||' % request_string
        s = socket.socket()
        s.settimeout(15)
        print "Attempting to connect to %s on port %s" %(address, port)
        try:
            s.connect((address, port))
            s.send(request_string)
            rsp = s.recv(1024)

        except socket.error, e:
            print "Connection to %s on port %s failed: %s" %(address, port, e)
            return False
        finally:
            print "Closing the connection"
            s.close()
        try:
            locationList = re.findall("Location: (.*)", rsp)
            location="/"
            if len(locationList)!=0:
                location +=locationList[0].strip("\r\n").split("/")[-1]
            print("Locatin : %s"% location)
        except:
            pass
        try:
            lines = rsp.splitlines()
            print 'First line of HTTP response: %s' % lines[0]
            version, status, message = re.split(r'\s+', lines[0], 2)
            print 'Version: %s, Stuats: %s, Message: %s' %(version, status, message)
        except ValueError:
            print 'Failed to split status line'
            return False
        if status in ['200', '302',"401"]:
            print 'Success - status was %s' %status
            with open("camera_IP.txt", "a+") as f:
                f.write(address + ":" + str(port) + location+"\n")
                f.close()
            return True
        else:
            print 'Staus was %s' %status
            return False

def scan_camera(ipPort):
        splitData = ipPort.split(":")
        ip = splitData[0]
        port = int(splitData[1])
        if check_webserver(ip,port):
            print"######"*25


# Check what time the scan started
t1 = datetime.now()
ipList=[]
with open("netwave.txt","r") as f:
    for line in f.readlines():
        ipList.append(line.strip("\n"))
print("test")
ports=[]        
for i in range(80,49152):
    ports.append(i)

def  getIpPortList(ipList,port):
    mIpPortList = []
    for ip in ipList:
        mIpPortList.append(ip+":"+str(port))
    return mIpPortList

for port in ports:
    ipPortList=getIpPortList(ipList,port)
    pool = ThreadPool(processes = 8)
    results = pool.map(scan_camera,ipPortList)
    pool.close()
    pool.join()

print 'Multiprocess Scanning Completed in  ', datetime.now() - t1

你可能感兴趣的:(python)