コード例 #1
0
def FiletimeToDateTime(h):
    from filetimes import filetime_to_dt
    val = h.value()

    time = filetime_to_dt(val)

    return str(time) + " UTC"
コード例 #2
0
ファイル: kmsBase.py プロジェクト: dapao9999/py-kms
    def serverLogic(self, kmsRequest):
        if self.config['debug']:
            print "KMS Request Bytes:", binascii.b2a_hex(str(kmsRequest))
            print "KMS Request:", kmsRequest.dump()

        if self.config['verbose']:
            clientMachineId = kmsRequest['clientMachineId'].get()
            applicationId = kmsRequest['applicationId'].get()
            skuId = kmsRequest['skuId'].get()
            requestDatetime = filetimes.filetime_to_dt(
                kmsRequest['requestTime'])

            # Try and localize the request time, if pytz is available
            try:
                import timezones
                from pytz import utc
                local_dt = utc.localize(requestDatetime).astimezone(
                    timezones.localtz())
            except ImportError:
                local_dt = requestDatetime

            print "     Machine Name: %s" % kmsRequest.getMachineName()
            print "Client Machine ID: %s" % str(clientMachineId)
            print "   Application ID: %s" % self.appIds.get(
                applicationId, str(applicationId))
            print "           SKU ID: %s" % self.skuIds.get(skuId, str(skuId))
            print "   Licence Status: %s" % kmsRequest.getLicenseStatus()
            print "     Request Time: %s" % local_dt.strftime(
                '%Y-%m-%d %H:%M:%S %Z (UTC%z)')

        return self.createKmsResponse(kmsRequest)
コード例 #3
0
ファイル: kmsBase.py プロジェクト: zxiaofan/py-kms
    def serverLogic(self, kmsRequest):
        if self.config["debug"]:
            print "KMS Request Bytes:", binascii.b2a_hex(str(kmsRequest))
            print "KMS Request:", kmsRequest.dump()

        if self.config["verbose"]:
            clientMachineId = kmsRequest["clientMachineId"].get()
            applicationId = kmsRequest["applicationId"].get()
            skuId = kmsRequest["skuId"].get()
            requestDatetime = filetimes.filetime_to_dt(kmsRequest["requestTime"])

            # Try and localize the request time, if pytz is available
            try:
                import timezones
                from pytz import utc

                local_dt = utc.localize(requestDatetime).astimezone(timezones.localtz())
            except ImportError:
                local_dt = requestDatetime

            print "     Machine Name: %s" % kmsRequest.getMachineName()
            print "Client Machine ID: %s" % str(clientMachineId)
            print "   Application ID: %s" % self.appIds.get(applicationId, str(applicationId))
            print "           SKU ID: %s" % self.skuIds.get(skuId, str(skuId))
            print "   Licence Status: %s" % kmsRequest.getLicenseStatus()
            print "     Request Time: %s" % local_dt.strftime("%Y-%m-%d %H:%M:%S %Z (UTC%z)")

        return self.createKmsResponse(kmsRequest)
コード例 #4
0
ファイル: kmsBase.py プロジェクト: SourceDoctor/py-kms
	def serverLogic(self, kmsRequest):
		logging.debug("KMS Request Bytes:", binascii.b2a_hex(str(kmsRequest)))
		logging.debug("KMS Request:", kmsRequest.dump())

		clientMachineId = kmsRequest['clientMachineId'].get()
		applicationId = kmsRequest['applicationId'].get()
		skuId = kmsRequest['skuId'].get()
		requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime'])

		# Try and localize the request time, if pytz is available
		try:
			import timezones
			from pytz import utc
			local_dt = utc.localize(requestDatetime).astimezone(timezones.localtz())
		except ImportError:
			local_dt = requestDatetime

		logging.info("	Machine Name: %s" % kmsRequest.getMachineName())
		logging.info("	Client Machine ID: %s" % str(clientMachineId))
		logging.info("	Application ID: %s" % self.appIds.get(applicationId, str(applicationId)))
		logging.info("	SKU ID: %s" % self.skuIds.get(skuId, str(skuId)))
		logging.info("	License Status: %s" % kmsRequest.getLicenseStatus())
		logging.info("	Request Time: %s" % local_dt.strftime('%Y-%m-%d %H:%M:%S %Z (UTC%z)'))

		return self.createKmsResponse(kmsRequest)
コード例 #5
0
def FiletimeToDateTime(h):
    from filetimes import filetime_to_dt
    val = h.value()

    time = filetime_to_dt(val)

    return str(time) + " UTC"
コード例 #6
0
ファイル: getwmipatches.py プロジェクト: truekonrads/kwmic
def getHotfixes(computername,username=None,password=None,debug=False):
    hotfixes=[]
    # realHostName=None
    try:
        if isWindowsListening(computername,debug) is False:
            return []
        if username and password:            
            w=wmi.WMI(computername,user=username,password=password)
        else:
            w=wmi.WMI(computername)
        
        if debug:
            print "[DD] Connected to {}".format(computername)
        for kb in w.Win32_QuickFixEngineering():
            hfx={}
            # if realHostName is None:
                # realHostName=kb.CSName
            for attr in FIXATTRS:
                hfx[attr]=getattr(kb,attr)
            if len(hfx["InstalledOn"])==16: # hex date
                hfx["InstalledOn"]=filetime_to_dt(int(hfx["InstalledOn"],16)).strftime("%Y/%m/%d")
            if hfx["InstalledOn"].find("/")==-1:
                hfx["InstalledOn"]="{}/{}/{}".format(hfx["InstalledOn"][0:4],hfx["InstalledOn"][4:6],hfx["InstalledOn"][6:8])
            hotfixes.append(hfx)
        if debug:
            print "[DD] Got {} hotfixes from {}".format(len(hotfixes),computername)
        return hotfixes


    except (wmi.x_wmi,socket.timeout,socket.error),x:
        print "[EE] Can't connect to computername: {}".format(computername)
        print x
        return (computername,[])
コード例 #7
0
                    sys.exit(1)

                finally:
                    if con:
                        con.commit()
                        con.close()

        logging.debug("KMS Request Bytes: %s" %
                      binascii.b2a_hex(str(kmsRequest)))
        logging.debug("KMS Request: %s" % kmsRequest.dump())

        clientMachineId = kmsRequest['clientMachineId'].get()
        global applicationId
        applicationId = kmsRequest['applicationId'].get()
        skuId = kmsRequest['skuId'].get()
        requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime'])

        # Try and localize the request time, if pytz is available
        try:
            import timezones
            from pytz import utc
            local_dt = utc.localize(requestDatetime).astimezone(
                timezones.localtz())
        except ImportError:
            local_dt = requestDatetime

        infoDict = {
            "machineName": kmsRequest.getMachineName(),
            "clientMachineId": str(clientMachineId),
            "appId": self.appIds.get(applicationId, str(applicationId)),
            "skuId": self.skuIds.get(skuId, str(skuId)),
コード例 #8
0
ファイル: kmsBase.py プロジェクト: zod331/py-kms-1
    def serverLogic(self, kmsRequest):
        if self.config['sqlite'] and self.config['dbSupport']:
            self.dbName = 'clients.db'
            if not os.path.isfile(self.dbName):
                # Initialize the database.
                con = None
                try:
                    con = sqlite3.connect(self.dbName)
                    cur = con.cursor()
                    cur.execute(
                        "CREATE TABLE clients(clientMachineId TEXT, machineName TEXT, \
applicationId TEXT, skuId TEXT, licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)"
                    )

                except sqlite3.Error as e:  #*2to3*
                    logging.error("%s:" % e.args[0])
                    sys.exit(1)

                finally:
                    if con:
                        con.commit()
                        con.close()

        shell_message(nshell=15)
        kmsRequest = byterize(kmsRequest)
        logging.debug("KMS Request Bytes: \n%s\n" % justify(
            binascii.b2a_hex(
                str(kmsRequest).encode('latin-1')).decode('utf-8')))  #*2to3*
        logging.debug("KMS Request: \n%s\n" %
                      justify(kmsRequest.dump(print_to_stdout=False)))

        clientMachineId = kmsRequest['clientMachineId'].get()
        applicationId = kmsRequest['applicationId'].get()
        skuId = kmsRequest['skuId'].get()
        requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime'])

        # Try and localize the request time, if pytz is available
        try:
            import timezones
            from pytz import utc
            local_dt = utc.localize(requestDatetime).astimezone(
                timezones.localtz())
        except ImportError:
            local_dt = requestDatetime

        infoDict = {
            "machineName": kmsRequest.getMachineName(),
            "clientMachineId": str(clientMachineId),
            "appId": self.appIds.get(applicationId, str(applicationId)),
            "skuId": self.skuIds.get(skuId, str(skuId)),
            "licenseStatus": kmsRequest.getLicenseStatus(),
            "requestTime": int(time.time()),
            "kmsEpid": None
        }

        #print infoDict
        logging.info("Machine Name: %s" % infoDict["machineName"])
        logging.info("Client Machine ID: %s" % infoDict["clientMachineId"])
        logging.info("Application ID: %s" % infoDict["appId"])
        logging.info("SKU ID: %s" % infoDict["skuId"])
        logging.info("License Status: %s" % infoDict["licenseStatus"])
        logging.info("Request Time: %s" %
                     local_dt.strftime('%Y-%m-%d %H:%M:%S %Z (UTC%z)'))

        if self.config['sqlite'] and self.config['dbSupport']:
            con = None
            try:
                con = sqlite3.connect(self.dbName)
                cur = con.cursor()
                cur.execute(
                    "SELECT * FROM clients WHERE clientMachineId=:clientMachineId;",
                    infoDict)
                try:
                    data = cur.fetchone()
                    if not data:
                        #print "Inserting row..."
                        cur.execute(
                            "INSERT INTO clients (clientMachineId, machineName, \
applicationId, skuId, licenseStatus, lastRequestTime, requestCount) VALUES (:clientMachineId, :machineName, :appId, \
:skuId, :licenseStatus, :requestTime, 1);", infoDict)
                    else:
                        #print "Data:", data
                        if data[1] != infoDict["machineName"]:
                            cur.execute(
                                "UPDATE clients SET machineName=:machineName WHERE \
clientMachineId=:clientMachineId;", infoDict)
                        if data[2] != infoDict["appId"]:
                            cur.execute(
                                "UPDATE clients SET applicationId=:appId WHERE \
clientMachineId=:clientMachineId;", infoDict)
                        if data[3] != infoDict["skuId"]:
                            cur.execute(
                                "UPDATE clients SET skuId=:skuId WHERE \
clientMachineId=:clientMachineId;", infoDict)
                        if data[4] != infoDict["licenseStatus"]:
                            cur.execute(
                                "UPDATE clients SET licenseStatus=:licenseStatus WHERE \
clientMachineId=:clientMachineId;", infoDict)
                        if data[5] != infoDict["requestTime"]:
                            cur.execute(
                                "UPDATE clients SET lastRequestTime=:requestTime WHERE \
clientMachineId=:clientMachineId;", infoDict)
                        # Increment requestCount
                        cur.execute(
                            "UPDATE clients SET requestCount=requestCount+1 WHERE \
clientMachineId=:clientMachineId;", infoDict)

                except sqlite3.Error as e:  #*2to3*
                    logging.error("%s:" % e.args[0])

            except sqlite3.Error as e:  #*2to3*
                logging.error("%s:" % e.args[0])
                sys.exit(1)
            finally:
                if con:
                    con.commit()
                    con.close()

        return self.createKmsResponse(kmsRequest)
コード例 #9
0
    def serverLogic(self, kmsRequest):
        if self.config['sqlite'] and self.config['dbSupport']:
            self.dbName = 'clients.db'
            if not os.path.isfile(self.dbName):
                # Initialize the database.
                con = None
                try:
                    con = sqlite3.connect(self.dbName)
                    cur = con.cursor()
                    cur.execute(
                        "CREATE TABLE clients(clientMachineId TEXT, machineName TEXT, applicationId TEXT, \
skuId TEXT, licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)"
                    )

                except sqlite3.Error as e:
                    logger.error("Error %s:" % e.args[0])
                    sys.exit(1)

                finally:
                    if con:
                        con.commit()
                        con.close()

        shell_message(nshell=15)
        kmsRequest = byterize(kmsRequest)
        logger.debug("KMS Request Bytes: \n%s\n" % justify(
            binascii.b2a_hex(
                str(kmsRequest).encode('latin-1')).decode('utf-8')))
        logger.debug("KMS Request: \n%s\n" %
                     justify(kmsRequest.dump(print_to_stdout=False)))

        clientMachineId = kmsRequest['clientMachineId'].get()
        applicationId = kmsRequest['applicationId'].get()
        skuId = kmsRequest['skuId'].get()
        requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime'])

        # Localize the request time, if module "tzlocal" is available.
        try:
            from tzlocal import get_localzone
            from pytz.exceptions import UnknownTimeZoneError
            try:
                tz = get_localzone()
                local_dt = tz.localize(requestDatetime)
            except UnknownTimeZoneError:
                logger.warning(
                    'Unknown time zone ! Request time not localized.')
                local_dt = requestDatetime
        except ImportError:
            logger.warning(
                'Module "tzlocal" not available ! Request time not localized.')
            local_dt = requestDatetime

        # Get SkuId, AppId and client threshold.
        appName, skuName = applicationId, skuId

        kmsdb = kmsDB2Dict()

        appitems = kmsdb[2]
        for appitem in appitems:
            kmsitems = appitem['KmsItems']
            for kmsitem in kmsitems:
                # Activation threshold.
                try:
                    count = int(kmsitem['NCountPolicy'])
                except KeyError:
                    count = 25

                if self.config["CurrentClientCount"] <= count:
                    currentClientCount = count + 1
                else:
                    currentClientCount = self.config["CurrentClientCount"]

                skuitems = kmsitem['SkuItems']
                for skuitem in skuitems:
                    try:
                        if uuid.UUID(skuitem['Id']) == skuId:
                            skuName = skuitem['DisplayName']
                            break
                    except IndexError:
                        pass

            if uuid.UUID(appitem['Id']) == applicationId:
                appName = appitem['DisplayName']

        infoDict = {
            "machineName": kmsRequest.getMachineName(),
            "clientMachineId": str(clientMachineId),
            "appId": appName,
            "skuId": skuName,
            "licenseStatus": kmsRequest.getLicenseStatus(),
            "requestTime": int(time.time()),
            "kmsEpid": None
        }

        #print infoDict
        logger.info("Machine Name: %s" % infoDict["machineName"])
        logger.info("Client Machine ID: %s" % infoDict["clientMachineId"])
        logger.info("Application ID: %s" % infoDict["appId"])
        logger.info("SKU ID: %s" % infoDict["skuId"])
        logger.info("License Status: %s" % infoDict["licenseStatus"])
        logger.info("Request Time: %s" %
                    local_dt.strftime('%Y-%m-%d %H:%M:%S %Z (UTC%z)'))

        if self.config['sqlite'] and self.config['dbSupport']:
            con = None
            try:
                con = sqlite3.connect(self.dbName)
                cur = con.cursor()
                cur.execute(
                    "SELECT * FROM clients WHERE clientMachineId=:clientMachineId;",
                    infoDict)
                try:
                    data = cur.fetchone()
                    if not data:
                        #print "Inserting row..."
                        cur.execute(
                            "INSERT INTO clients (clientMachineId, machineName, applicationId, \
skuId, licenseStatus, lastRequestTime, requestCount) VALUES (:clientMachineId, :machineName, :appId, :skuId, :licenseStatus, :requestTime, 1);",
                            infoDict)
                    else:
                        #print "Data:", data
                        if data[1] != infoDict["machineName"]:
                            cur.execute(
                                "UPDATE clients SET machineName=:machineName WHERE \
clientMachineId=:clientMachineId;", infoDict)
                        if data[2] != infoDict["appId"]:
                            cur.execute(
                                "UPDATE clients SET applicationId=:appId WHERE \
clientMachineId=:clientMachineId;", infoDict)
                        if data[3] != infoDict["skuId"]:
                            cur.execute(
                                "UPDATE clients SET skuId=:skuId WHERE \
clientMachineId=:clientMachineId;", infoDict)
                        if data[4] != infoDict["licenseStatus"]:
                            cur.execute(
                                "UPDATE clients SET licenseStatus=:licenseStatus WHERE \
clientMachineId=:clientMachineId;", infoDict)
                        if data[5] != infoDict["requestTime"]:
                            cur.execute(
                                "UPDATE clients SET lastRequestTime=:requestTime WHERE \
clientMachineId=:clientMachineId;", infoDict)
                        # Increment requestCount
                        cur.execute(
                            "UPDATE clients SET requestCount=requestCount+1 WHERE \
clientMachineId=:clientMachineId;", infoDict)

                except sqlite3.Error as e:
                    logger.error("Error %s:" % e.args[0])

            except sqlite3.Error as e:
                logger.error("Error %s:" % e.args[0])
                sys.exit(1)
            finally:
                if con:
                    con.commit()
                    con.close()

        return self.createKmsResponse(kmsRequest, currentClientCount)
コード例 #10
0
ファイル: kmsBase.py プロジェクト: asaboss/docker-py-kms
					print "Error %s:" % e.args[0]
					sys.exit(1)

				finally:
					if con:
						con.commit()
						con.close()

		if self.config['debug']:
			print "KMS Request Bytes:", binascii.b2a_hex(str(kmsRequest))
			print "KMS Request:", kmsRequest.dump()

		clientMachineId = kmsRequest['clientMachineId'].get()
		applicationId = kmsRequest['applicationId'].get()
		skuId = kmsRequest['skuId'].get()
		requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime'])

		# Try and localize the request time, if pytz is available
		try:
			import timezones
			from pytz import utc
			local_dt = utc.localize(requestDatetime).astimezone(timezones.localtz())
		except ImportError:
			local_dt = requestDatetime

		infoDict = {
			"machineName" : kmsRequest.getMachineName(),
			"clientMachineId" : str(clientMachineId),
			"appId" : self.appIds.get(applicationId, str(applicationId)),
			"skuId" : self.skuIds.get(skuId, str(skuId)),
			"licenseStatus" : kmsRequest.getLicenseStatus(),
コード例 #11
0
ファイル: kmsBase.py プロジェクト: downloadmorerum/py-kms
        def serverLogic(self, kmsRequest):
                if self.config['sqlite'] and self.config['dbSupport']:
                        self.dbName = 'clients.db'
                        if not os.path.isfile(self.dbName):
                                # Initialize the database.
                                con = None
                                try:
                                        con = sqlite3.connect(self.dbName)
                                        cur = con.cursor()
                                        cur.execute("CREATE TABLE clients(clientMachineId TEXT, machineName TEXT, \
applicationId TEXT, skuId TEXT, licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)")

                                except sqlite3.Error as e: #*2to3*
                                        logging.error("%s:" % e.args[0])
                                        sys.exit(1)

                                finally:
                                        if con:
                                                con.commit()
                                                con.close()

                shell_message(nshell = 15)
                kmsRequest = byterize(kmsRequest)
                logging.debug("KMS Request Bytes: \n%s\n" % justify(binascii.b2a_hex(str(kmsRequest).encode('latin-1')).decode('utf-8'))) #*2to3*                          
                logging.debug("KMS Request: \n%s\n" % justify(kmsRequest.dump(print_to_stdout = False)))
                                        
                clientMachineId = kmsRequest['clientMachineId'].get()
                applicationId = kmsRequest['applicationId'].get()
                skuId = kmsRequest['skuId'].get()
                requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime'])

                # Try and localize the request time, if pytz is available
                try:
                        import timezones
                        from pytz import utc
                        local_dt = utc.localize(requestDatetime).astimezone(timezones.localtz())
                except ImportError:
                        local_dt = requestDatetime

                infoDict = {
                        "machineName" : kmsRequest.getMachineName(),
                        "clientMachineId" : str(clientMachineId),
                        "appId" : self.appIds.get(applicationId, str(applicationId)),
                        "skuId" : self.skuIds.get(skuId, str(skuId)),
                        "licenseStatus" : kmsRequest.getLicenseStatus(),
                        "requestTime" : int(time.time()),
                        "kmsEpid" : None
                }

                #print infoDict
                logging.info("Machine Name: %s" % infoDict["machineName"])
                logging.info("Client Machine ID: %s" % infoDict["clientMachineId"])
                logging.info("Application ID: %s" % infoDict["appId"])
                logging.info("SKU ID: %s" % infoDict["skuId"])
                logging.info("License Status: %s" % infoDict["licenseStatus"])
                logging.info("Request Time: %s" % local_dt.strftime('%Y-%m-%d %H:%M:%S %Z (UTC%z)'))

                if self.config['sqlite'] and self.config['dbSupport']:
                        con = None
                        try:
                                con = sqlite3.connect(self.dbName)
                                cur = con.cursor()
                                cur.execute("SELECT * FROM clients WHERE clientMachineId=:clientMachineId;", infoDict)
                                try:
                                        data = cur.fetchone()
                                        if not data:
                                                #print "Inserting row..."
                                                cur.execute("INSERT INTO clients (clientMachineId, machineName, \
applicationId, skuId, licenseStatus, lastRequestTime, requestCount) VALUES (:clientMachineId, :machineName, :appId, \
:skuId, :licenseStatus, :requestTime, 1);", infoDict)
                                        else:
                                                #print "Data:", data
                                                if data[1] != infoDict["machineName"]:
                                                        cur.execute("UPDATE clients SET machineName=:machineName WHERE \
clientMachineId=:clientMachineId;", infoDict)
                                                if data[2] != infoDict["appId"]:
                                                        cur.execute("UPDATE clients SET applicationId=:appId WHERE \
clientMachineId=:clientMachineId;", infoDict)
                                                if data[3] != infoDict["skuId"]:
                                                        cur.execute("UPDATE clients SET skuId=:skuId WHERE \
clientMachineId=:clientMachineId;", infoDict)
                                                if data[4] != infoDict["licenseStatus"]:
                                                        cur.execute("UPDATE clients SET licenseStatus=:licenseStatus WHERE \
clientMachineId=:clientMachineId;", infoDict)
                                                if data[5] != infoDict["requestTime"]:
                                                        cur.execute("UPDATE clients SET lastRequestTime=:requestTime WHERE \
clientMachineId=:clientMachineId;", infoDict)
                                                # Increment requestCount
                                                cur.execute("UPDATE clients SET requestCount=requestCount+1 WHERE \
clientMachineId=:clientMachineId;", infoDict)

                                except sqlite3.Error as e: #*2to3*
                                        logging.error("%s:" % e.args[0])
                                        
                        except sqlite3.Error as e: #*2to3*
                                logging.error("%s:" % e.args[0])
                                sys.exit(1)
                        finally:
                                if con:
                                        con.commit()
                                        con.close()

                return self.createKmsResponse(kmsRequest)
コード例 #12
0
ファイル: adgroup.py プロジェクト: popoff1998/ScriptsAdm
for user in q.get_results():
    lista_usuarios.append(user)
print "Hay ",len(lista_usuarios)," alumnos"

print "Comprobando la membresia a UCOUSERS"
procesados = 0
isiterable = lambda obj: isinstance(obj, basestring) \
    or getattr(obj, '__iter__', False)
for user in lista_usuarios:
    es_miembro = False
    procesados = procesados + 1
    print "Procesados: ",procesados
    #Si memberOf no es iterable es que no tiene ningun grupo    
    if isiterable(user['memberOf']):
        #Para cada usuario miramos la lista de grupos    
        for group in user['memberOf']:
            #Vemos si el literal UCOUSERS esta en ese grupo
            if "UCOUSERS" in group:
                es_miembro = True
    if not es_miembro:        
        lista_nomiembros.append(user)

print "Hay ",len(lista_usuarios)," alumnos"
print "Hay ",len(lista_nomiembros)," alumnos que no están en ucousers"
print "La lista de usuarios es:"
for user in lista_nomiembros:
    pyad.ADObject.get_attribute()
    aduser=pyad.from_cn(user['sAMAccountName'])
    exp_date = aduser.get
    print user['sAMAccountName'],filetimes.filetime_to_dt(user['accountExpires'])
コード例 #13
0
	def __init__(self, msg):
		self.body = msg.body.string
		self.sender = msg.sender.string
		self.recepients = [r.string for r in msg.recepients.findAll("string")]
		self.timestamp = filetime_to_dt(int(msg.localtimestamp.string))
コード例 #14
0
def get_date():
    return filetime_to_dt(details['m_timeUTC']).date()
コード例 #15
0
ファイル: kmsBase.py プロジェクト: zzzzzsh/py-kms
	def serverLogic(self, kmsRequest):
		if self.config['sqlite'] and self.config['dbSupport']:
			self.dbName = 'clients.db'
			if not os.path.isfile(self.dbName):
				# Initialize the database.
				con = None
				try:
					con = sqlite3.connect(self.dbName)
					cur = con.cursor()
					cur.execute("CREATE TABLE clients(clientMachineId TEXT, machineName TEXT, applicationId TEXT, skuId TEXT, licenseStatus TEXT, lastRequestTime INTEGER, kmsEpid TEXT, requestCount INTEGER)")

				except sqlite3.Error as e:
					print("Error %s:" % e.args[0])
					sys.exit(1)

				finally:
					if con:
						con.commit()
						con.close()

		if self.config['debug']:
			print("KMS Request Bytes:", binascii.b2a_hex(bytes(kmsRequest)))
			print("KMS Request:", kmsRequest.dump())

		clientMachineId = str(kmsRequest['clientMachineId'].get())
		applicationId = str(kmsRequest['applicationId'].get())
		skuId = str(kmsRequest['skuId'].get())
		requestDatetime = filetimes.filetime_to_dt(kmsRequest['requestTime'])

		# Try and localize the request time, if pytz is available
		try:
			import timezones
			from pytz import utc
			local_dt = utc.localize(requestDatetime).astimezone(timezones.localtz())
		except ImportError:
			local_dt = requestDatetime

		# activation threshold:
		# https://docs.microsoft.com/en-us/windows/deployment/volume-activation/activate-windows-10-clients-vamt
		kmsdata = parse(tokenize(open(kmsdb)), lesslist=False)['KmsData'][0]
		appName, skuName, currentClientCount = applicationId, skuId, 25
		for app in kmsdata['AppItem']:
			max_activ_thld = 0
			for kms in app['KmsItem']:
				max_activ_thld = max(max_activ_thld, int(kms.get('@NCountPolicy', 25)))
				for sku in kms.get('SkuItem', []):
					if sku['@Id'] == skuId:
						skuName = sku['@DisplayName']
			if app['@Id'] == applicationId:
				appName = app['@DisplayName']
				currentClientCount = max_activ_thld * 2

		infoDict = {
			"machineName" : kmsRequest.getMachineName(),
			"clientMachineId" : clientMachineId,
			"appId" : appName,
			"skuId" : skuName,
			"licenseStatus" : kmsRequest.getLicenseStatus(),
			"requestTime" : int(time.time()),
			"kmsEpid" : None
		}

		#print infoDict

		if self.config['verbose']:
			print("     Machine Name: %s" % infoDict["machineName"])
			print("Client Machine ID: %s" % infoDict["clientMachineId"])
			print("   Application ID: %s" % infoDict["appId"])
			print("           SKU ID: %s" % infoDict["skuId"])
			print("   Licence Status: %s" % infoDict["licenseStatus"])
			print("     Request Time: %s" % local_dt.strftime('%Y-%m-%d %H:%M:%S %Z (UTC%z)'))

		if self.config['sqlite'] and self.config['dbSupport']:
			con = None
			try:
				con = sqlite3.connect(self.dbName)
				cur = con.cursor()
				cur.execute("SELECT * FROM clients WHERE clientMachineId=:clientMachineId;", infoDict)
				try:
					data = cur.fetchone()
					if not data:
						#print "Inserting row..."
						cur.execute("INSERT INTO clients (clientMachineId, machineName, applicationId, skuId, licenseStatus, lastRequestTime, requestCount) VALUES (:clientMachineId, :machineName, :appId, :skuId, :licenseStatus, :requestTime, 1);", infoDict)
					else:
						#print "Data:", data
						if data[1] != infoDict["machineName"]:
							cur.execute("UPDATE clients SET machineName=:machineName WHERE clientMachineId=:clientMachineId;", infoDict)
						if data[2] != infoDict["appId"]:
							cur.execute("UPDATE clients SET applicationId=:appId WHERE clientMachineId=:clientMachineId;", infoDict)
						if data[3] != infoDict["skuId"]:
							cur.execute("UPDATE clients SET skuId=:skuId WHERE clientMachineId=:clientMachineId;", infoDict)
						if data[4] != infoDict["licenseStatus"]:
							cur.execute("UPDATE clients SET licenseStatus=:licenseStatus WHERE clientMachineId=:clientMachineId;", infoDict)
						if data[5] != infoDict["requestTime"]:
							cur.execute("UPDATE clients SET lastRequestTime=:requestTime WHERE clientMachineId=:clientMachineId;", infoDict)
						# Increment requestCount
						cur.execute("UPDATE clients SET requestCount=requestCount+1 WHERE clientMachineId=:clientMachineId;", infoDict)

				except sqlite3.Error as e:
					print("Error %s:" % e.args[0])

			except sqlite3.Error as e:
				print("Error %s:" % e.args[0])
				sys.exit(1)

			finally:
				if con:
					con.commit()
					con.close()

		return self.createKmsResponse(kmsRequest, currentClientCount)