Esempio n. 1
0
def __StopServiceWithTimeout(hs, waitSecs=30):
    try:
        status = win32service.ControlService(hs,
                                             win32service.SERVICE_CONTROL_STOP)
    except pywintypes.error as exc:
        if exc.winerror != winerror.ERROR_SERVICE_NOT_ACTIVE:
            raise
    for i in range(waitSecs):
        status = win32service.QueryServiceStatus(hs)
        if status[1] == win32service.SERVICE_STOPPED:
            break
        win32api.Sleep(1000)
    else:
        raise pywintypes.error(
            winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "ControlService",
            win32api.FormatMessage(
                winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])
Esempio n. 2
0
def adduser(name, username, **kwargs):
    """
    Add a user to a group

    Args:

        name (str):
            The name of the group to modify

        username (str):
            The name of the user to add to the group

    Returns:
        bool: ``True`` if successful, otherwise ``False``

    CLI Example:

    .. code-block:: bash

        salt '*' group.adduser foo username
    """
    try:
        group_obj = _get_group_object(name)
    except pywintypes.com_error as exc:
        log.error(
            "Failed to access group %s. %s",
            name,
            win32api.FormatMessage(exc.excepinfo[5]),
        )
        return False

    existing_members = [_get_username(x) for x in group_obj.members()]
    username = salt.utils.win_functions.get_sam_name(username)

    try:
        if username not in existing_members:
            group_obj.Add("WinNT://" + username.replace("\\", "/"))
            log.info("Added user %s", username)
        else:
            log.warning("User %s is already a member of %s", username, name)
            return False
    except pywintypes.com_error as exc:
        log.error("Failed to add %s to group %s. %s", username, name, exc.excepinfo[2])
        return False

    return True
Esempio n. 3
0
    def _subscribe_to_events(self):
        """
            Go through all channels, and create an event subscription to that channel.
            If a bookmark exists for a given channel, start the events from that bookmark, otherwise subscribe
            to future events only.
        """

        for info in self.__channels:
            channel_list = info["channel"]
            query = info["query"]
            for channel in channel_list:
                self._logger.info("subscribing to %s, %s", channel, query)
                # subscribe to future events
                flags = win32evtlog.EvtSubscribeToFutureEvents
                bookmark = None
                try:
                    # unless we have a bookmark for this channel
                    self.__bookmark_lock.acquire()
                    if channel in self.__bookmarks:
                        flags = win32evtlog.EvtSubscribeStartAfterBookmark
                        bookmark = self.__bookmarks[channel]
                finally:
                    self.__bookmark_lock.release()

                error_message = None
                try:
                    handle = win32evtlog.EvtSubscribe(
                        channel,
                        flags,
                        Bookmark=bookmark,
                        Query=query,
                        Callback=event_callback,
                        Context=self,
                        Session=self._session,
                    )
                except Exception:
                    handle = None
                    error_message = win32api.FormatMessage(0)

                if handle is None:
                    self._logger.warn(
                        "Error subscribing to channel '%s' - %s" %
                        (channel, error_message))
                else:
                    self.__eventHandles.append(handle)
Esempio n. 4
0
    def _read_mem_address(self, raw_address, size, handle):
        buf = (c_byte * size)()
        bytesRead = c_ulong(0)
        result = None

        try:
            result = ctypes.windll.kernel32.ReadProcessMemory(
                handle, raw_address, buf, size, ctypes.byref(bytesRead))

            assert result != 0
            return buf

        except Exception as e:
            err = ctypes.windll.kernel32.GetLastError()
            err_msg = win32api.FormatMessage(result).strip()

            raise RuntimeError(
                f"Could not read address {raw_address} ({size}B), error code {result} ({err_msg})"
            )
Esempio n. 5
0
 def CleanUp(self):
     "Free Memory and the process handle"
     if self.process != 0 and self.memAddress != 0:
         # free up the memory we allocated
         #win32api.SetLastError(0)
         self.CheckGuardSignature()
         
         ret = win32functions.VirtualFreeEx(
             ctypes.c_void_p(self.process), ctypes.c_void_p(self.memAddress), win32structures.ULONG_PTR(0), win32structures.DWORD(win32defines.MEM_RELEASE))
         if ret == 0:
             print('Error: CleanUp: VirtualFreeEx() returned zero for address ', hex(self.memAddress))
             last_error = win32api.GetLastError()
             print('LastError = ', last_error, ': ', win32api.FormatMessage(last_error).rstrip())
             sys.stdout.flush()
             #self._CloseHandle()
             raise ctypes.WinError()
         self.memAddress = 0
         #self._CloseHandle()
     else:
         pass #ActionLogger().log('\nWARNING: Cannot call VirtualFreeEx! process_id == 0.')
Esempio n. 6
0
    def openFileInExistingVisualStudioInstance(self, filePath, lineNo):
        try:
            vsPath = self._varMgr.expand('[VisualStudioIdePath]')

            if '2017' in vsPath or 'Visual Studio 15.0' in vsPath:
                dte = win32com.client.GetActiveObject("VisualStudio.DTE.15.0")
            elif 'Visual Studio 14.0' in vsPath:
                dte = win32com.client.GetActiveObject("VisualStudio.DTE.14.0")
            elif 'Visual Studio 12.0' in vsPath:
                dte = win32com.client.GetActiveObject("VisualStudio.DTE.12.0")
            else:
                assertThat(False, "Could not determine visual studio version")

            dte.MainWindow.Activate
            dte.ItemOperations.OpenFile(self._sys.canonicalizePath(filePath))
            dte.ActiveDocument.Selection.MoveToLineAndOffset(lineNo, 1)
        except Exception as error:
            raise Exception(
                "COM Error.  This is often triggered when given a bad line number. Details: {0}"
                .format(win32api.FormatMessage(error.excepinfo[5])))
Esempio n. 7
0
    def Connect(self):
        """
        This function tries to connect to the named pipe from AlternateMceIrService.  If it can't connect, it will periodically
        retry until the plugin is stopped or the connection is made.
        """
        self.connecting = True
        #eg.PrintNotice("MCE_Vista: Connect started")
        while self.file is None and self.keepRunning:
            self.SetReceiving(False)
            try:
                self.file = win32file.CreateFile(
                    r'\\.\pipe\MceIr', win32file.GENERIC_READ
                    | win32file.GENERIC_WRITE, 0, None,
                    win32file.OPEN_EXISTING, win32file.FILE_ATTRIBUTE_NORMAL
                    | win32file.FILE_FLAG_OVERLAPPED, None)
                if self.sentMessageOnce:
                    eg.PrintNotice(
                        "MCE_Vista: Connected to MceIr pipe, started handling IR events"
                    )
                    self.plugin.TriggerEvent("Connected")
                    self.sentMessageOnce = False
            except:
                if not self.sentMessageOnce:
                    eg.PrintNotice(
                        "MCE_Vista: MceIr pipe is not available, app doesn't seem to be running"
                    )
                    eg.PrintNotice(
                        "    Will continue to try to connect to MceIr")
                    eg.PrintNotice(
                        "    Message = %s" %
                        win32api.FormatMessage(win32api.GetLastError()))
                    self.plugin.TriggerEvent("Disconnected")
                    self.sentMessageOnce = True

                #if self.service and IsServiceStopped(self.service):
                #    eg.PrintNotice("MCE_Vista: MceIr service is stopped, trying to start it...")
                #    StartService(self.service)

                time.sleep(1)
        self.connecting = False
        return
Esempio n. 8
0
    def read(self, length=1024):
        #buf = win32file.AllocateReadBuffer(length)
        try:
            #(hr, result) = win32file.ReadFile(self.handle, buf, None)
            (hr, result) = win32file.ReadFile(self.handle, length, None)
        except win32api.error as exc:
            ec = win32api.FormatMessage()
            if exc.args[0] == ERROR_SEM_TIMEOUT:
                return buf
            else:
                raise
        if hr == 0:
            pass
        elif hr == ERROR_MORE_DATA:
            pass
        elif hr == ERROR_IO_PENDING:
            pass
        else:
            raise Exception("unknown return code '%u'." % hr)
#       return buf
        return result
Esempio n. 9
0
 def setpriority(pid = None, priority = 1):
     """ Set The Priority of a Windows Process.  Priority is a value between 0-5 where
         2 is normal priority.  Default sets the priority of the current
         python process but can take any valid process ID. """
     priorityclasses = [win32process.IDLE_PRIORITY_CLASS,
                        win32process.BELOW_NORMAL_PRIORITY_CLASS,
                        win32process.NORMAL_PRIORITY_CLASS,
                        win32process.ABOVE_NORMAL_PRIORITY_CLASS,
                        win32process.HIGH_PRIORITY_CLASS,
                        win32process.REALTIME_PRIORITY_CLASS]
     if pid == None:
         #pid = win32api.GetCurrentProcessId()
         pid = ctypes.windll.kernel32.GetCurrentProcessId()
     handle=ctypes.windll.kernel32.OpenProcess(win32con.PROCESS_ALL_ACCESS, True, pid)
     win32process.SetPriorityClass(handle, priorityclasses[priority])
     ## Chris
     win32process.SetProcessPriorityBoost(handle, False)
     ct = ctypes.windll.kernel32.GetCurrentThread()
     gle = win32api.GetLastError()
     print("gct", win32api.FormatMessage(gle))
     ctypes.windll.kernel32.SetThreadPriority(ct, win32con.THREAD_BASE_PRIORITY_LOWRT)
Esempio n. 10
0
 def Connect(self):
     """
     This function tries to connect to the named pipe from AlternateMceIrService.  If it can't connect, it will periodically
     retry until the plugin is stopped or the connection is made.
     """
     #eg.PrintNotice("MCE_Vista: Connect started")
     self.sentMessageOnce = False
     while self.file is None and self.keepRunning:
         try:
             self.file = win32file.CreateFile(r'\\.\pipe\MceIr',win32file.GENERIC_READ
                                     |win32file.GENERIC_WRITE,0,None,
                                     win32file.OPEN_EXISTING,win32file.FILE_ATTRIBUTE_NORMAL
                                     |win32file.FILE_FLAG_OVERLAPPED,None)
         except:
             if not self.sentMessageOnce:
                 eg.PrintNotice("MCE_Vista: MceIr pipe is not available, app doesn't seem to be running")
                 eg.PrintNotice("    Will continue to try to connect to MceIr")
                 eg.PrintNotice("    Message = %s"%win32api.FormatMessage(win32api.GetLastError()))
                 self.sentMessageOnce = True
             time.sleep(.25)
     return
    def _open_remote_session_if_necessary(self, server, config):
        """
            Opens a session to a remote server if `server` is not localhost or None
            @param server: string containing the server to connect to (can be None)
            @param config: a log config object
            @return: a valid session to a remote machine, or None if no remote session was needed
        """
        session = None

        # see if we need to create a remote connection
        if server is not None and server != "localhost":
            username = config.get("remote_user")
            password = config.get("remote_password")
            domain = config.get("remote_domain")
            flags = win32evtlog.EvtRpcLoginAuthDefault

            # login object is a tuple
            login = (server, username, domain, password, flags)
            self._logger.log(
                scalyr_logging.DEBUG_LEVEL_1,
                "Performing remote login: server - %s, user - %s, domain - %s"
                % (server, username, domain),
            )

            session = None
            session = win32evtlog.EvtOpenSession(login, win32evtlog.EvtRpcLogin, 0, 0)

            if session is None:
                # 0 means to call GetLastError for the error code
                error_message = win32api.FormatMessage(0)
                self._logger.warn(
                    "Error connecting to remote server %s, as %s - %s"
                    % (server, username, error_message)
                )
                raise Exception(
                    "Error connecting to remote server %s, as %s - %s"
                    % (server, username, error_message)
                )

        return session
Esempio n. 12
0
def create_daily_task(name, cmd, hour=None, minute=None):
    """creates a daily task"""
    cmd = cmd.split()
    ts = pythoncom.CoCreateInstance(taskscheduler.CLSID_CTaskScheduler,None,
                                    pythoncom.CLSCTX_INPROC_SERVER,
                                    taskscheduler.IID_ITaskScheduler)

    if '%s.job' % name not in ts.Enum():
        task = ts.NewWorkItem(name)
        task.SetApplicationName(cmd[0])
        task.SetParameters(' '.join(cmd[1:]))
        task.SetPriority(taskscheduler.REALTIME_PRIORITY_CLASS)
        task.SetFlags(taskscheduler.TASK_FLAG_RUN_ONLY_IF_LOGGED_ON)
        task.SetAccountInformation('', None)
        ts.AddWorkItem(name, task)
        run_time = time.localtime(time.time() + 300)
        tr_ind, tr = task.CreateTrigger()
        tt = tr.GetTrigger()
        tt.Flags = 0
        tt.BeginYear = int(time.strftime('%Y', run_time))
        tt.BeginMonth = int(time.strftime('%m', run_time))
        tt.BeginDay = int(time.strftime('%d', run_time))
        if minute is None:
            tt.StartMinute = int(time.strftime('%M', run_time))
        else:
            tt.StartMinute = minute
        if hour is None:
            tt.StartHour = int(time.strftime('%H', run_time))
        else:
            tt.StartHour = hour
        tt.TriggerType = int(taskscheduler.TASK_TIME_TRIGGER_DAILY)
        tr.SetTrigger(tt)
        pf = task.QueryInterface(pythoncom.IID_IPersistFile)
        pf.Save(None,1)
        task.Run()
    else:
        raise KeyError("%s already exists" % name)
    task = ts.Activate(name)
    exit_code, startup_error_code = task.GetExitCode()
    return win32api.FormatMessage(startup_error_code)
Esempio n. 13
0
    def screenShot(self):
        logger = logging.getLogger(__name__)
        logger.info("Taking snapshot")

        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(self.__mfcDC, self.__w, self.__h)

        self.__saveDC.SelectObject(saveBitMap)

        saveBitMap = win32ui.CreateBitmap()
        saveBitMap.CreateCompatibleBitmap(self.__mfcDC, self.__w, self.__h)

        self.__saveDC.SelectObject(saveBitMap)

        # Change the line below depending on whether you want the whole window
        # or just the client area.
        # result = windll.user32.PrintWindow(hwnd, saveDC.GetSafeHdc(), 1)
        result = windll.user32.PrintWindow(self.__hwnd, self.__saveDC.GetSafeHdc(), 0)

        if result == 1:
            logger.info('Snapshot taken successfully')
        else:
            err = win32api.GetLastError()
            msg = win32api.FormatMessage(err)
            logger.error("Cannot take snapshot, "
                         "Error %d: %s" % (err, msg))
            raise RuntimeError('Cannot Take Snapshot of Window')

        bmpinfo = saveBitMap.GetInfo()
        bmpstr = saveBitMap.GetBitmapBits(True)

        im = Image.frombuffer(
            'RGB',
            (bmpinfo['bmWidth'], bmpinfo['bmHeight']),
            bmpstr, 'raw', 'BGRX', 0, 1)

        win32gui.DeleteObject(saveBitMap.GetHandle())

        return im
Esempio n. 14
0
    def _GetProcessModules(self, ProcessID, isPrint):
        me32 = MODULEENTRY32()
        me32.dwSize = sizeof(MODULEENTRY32)
        hModuleSnap = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcessID)

        ret = Module32First(hModuleSnap, pointer(me32))
        if ret == 0:
            errCode = GetLastError()
            self.logger.warn('GetProcessModules() Error on Module32First[%d] with PID : %d' % (errCode, ProcessID))
            self.logger.warn(win32api.FormatMessage(errCode))
            CloseHandle(hModuleSnap)
            return []

        modules = []
        while ret:
            if isPrint:
                self.logger.info("   executable	 = %s" % me32.szExePath)
            modules.append(me32.szExePath)

            ret = Module32Next(hModuleSnap, pointer(me32))
        CloseHandle(hModuleSnap)
        return modules
Esempio n. 15
0
def ShowSystemErrorMessge(nError):
    #print "ShowSystemErrorMessge"
    #string = win32api.FormatMessage(errCode)
    lpMsgBuf = win32api.FormatMessage(\
        win32con.FORMAT_MESSAGE_ALLOCATE_BUFFER |\
        win32con.FORMAT_MESSAGE_FROM_SYSTEM |\
        win32con.FORMAT_MESSAGE_IGNORE_INSERTS,\
        NULL,\
        nError,\
        win32api.MAKELANGID(win32con.LANG_NEUTRAL, win32con.SUBLANG_NEUTRAL)\
        , None)

    #//format and show system error message
    #LPVOID lpMsgBuf;
    #FormatMessage(  FORMAT_MESSAGE_ALLOCATE_BUFFER |
    #                FORMAT_MESSAGE_FROM_SYSTEM |
    #                FORMAT_MESSAGE_IGNORE_INSERTS,
    #                NULL,
    #                nError,
    #                MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
    #                (LPTSTR) &lpMsgBuf, 0, NULL );
    wxMessageBox(lpMsgBuf, str(nError))
Esempio n. 16
0
def CreateProcessWithTokenW(
    token,
    logonflags=0,
    applicationname=None,
    commandline=None,
    creationflags=0,
    environment=None,
    currentdirectory=None,
    startupinfo=None,
):
    creationflags |= win32con.CREATE_UNICODE_ENVIRONMENT
    if commandline is not None:
        commandline = ctypes.create_unicode_buffer(commandline)
    if startupinfo is None:
        startupinfo = STARTUPINFO()
    if currentdirectory is not None:
        currentdirectory = ctypes.create_unicode_buffer(currentdirectory)
    if environment is not None:
        environment = ctypes.pointer(environment_string(environment))
    process_info = PROCESS_INFORMATION()
    ret = advapi32.CreateProcessWithTokenW(
        token,
        logonflags,
        applicationname,
        commandline,
        creationflags,
        environment,
        currentdirectory,
        ctypes.byref(startupinfo),
        ctypes.byref(process_info),
    )
    if ret == 0:
        winerr = win32api.GetLastError()
        # pylint: disable=undefined-variable
        exc = WindowsError(win32api.FormatMessage(winerr))
        # pylint: enable=undefined-variable
        exc.winerror = winerr
        raise exc
    return process_info
Esempio n. 17
0
    def Write(self, data, address=None, size=None):
        "Write data into the memory block"
        # write the data from this process into the memory allocated
        # from the other process
        if not address:
            address = self.memAddress
        if hasattr(address, 'value'):
            address = address.value

        if size:
            nSize = win32structures.ULONG_PTR(size)
        else:
            nSize = win32structures.ULONG_PTR(ctypes.sizeof(data))

        if self.size < nSize.value:
            raise Exception('Write: RemoteMemoryBlock is too small (' +
                            str(self.size) + ' bytes), ' + str(nSize.value) +
                            ' is required.')

        if hex(address).lower().startswith('0xffffff'):
            raise Exception(
                'Write: RemoteMemoryBlock has incorrect address = ' +
                hex(address))

        ret = win32functions.WriteProcessMemory(ctypes.c_void_p(self.process),
                                                ctypes.c_void_p(address),
                                                ctypes.pointer(data), nSize,
                                                win32structures.ULONG_PTR(0))

        if ret == 0:
            print('Error: Write failed: address = ', address)
            last_error = win32api.GetLastError()
            print('Error: LastError = ', last_error, ': ',
                  win32api.FormatMessage(last_error).rstrip())
            sys.stdout.flush()
            #raise ctypes.WinError()
        self.CheckGuardSignature()
Esempio n. 18
0
    def Write(self, data, address=None, size=None):
        """Write data into the memory block"""
        # write the data from this process into the memory allocated
        # from the other process
        if not address:
            address = self.mem_address
        if hasattr(address, 'value'):
            address = address.value

        if size:
            nSize = win32structures.ULONG_PTR(size)
        else:
            nSize = win32structures.ULONG_PTR(sizeof(data))

        if self.size < nSize.value:
            raise Exception(('Write: RemoteMemoryBlock is too small ({0} bytes),' +
                            ' {1} is required.').format(self.size, nSize.value))

        if hex(address).lower().startswith('0xffffff'):
            raise Exception('Write: RemoteMemoryBlock has incorrect address = ' + hex(address))

        ret = win32functions.WriteProcessMemory(
            c_void_p(self.process),
            c_void_p(address),
            pointer(data),
            nSize,
            win32structures.ULONG_PTR(0)
        )

        if ret == 0:
            ActionLogger().log('Error: Write failed: address = ' + str(address))
            last_error = win32api.GetLastError()
            ActionLogger().log('Error: LastError = ' + str(last_error) + ': ' +
                               win32api.FormatMessage(last_error).rstrip())
            raise WinError()
        self.CheckGuardSignature()
Esempio n. 19
0
def open_path_in_terminator(file_path):
    import locale
    err_code = ERROR_OK
    err_msg = ''
    sys_encoding = locale.getdefaultlocale()[1]
    if sysutils.isWindows():
        import ctypes
        import win32api
        try:
            subprocess.Popen('start cmd.exe',
                             shell=True,
                             cwd=file_path.encode(sys_encoding))
        except:
            err_code = ctypes.windll.kernel32.GetLastError()
            err_msg = win32api.FormatMessage(err_code)
    else:
        try:
            subprocess.Popen('gnome-terminal',
                             shell=True,
                             cwd=file_path.encode(sys_encoding))
        except Exception as e:
            err_code = UNKNOWN_ERROR
            err_msg = str(e)
    return err_code, err_msg
Esempio n. 20
0
 def testMessageIndex(self):
     exc = self._getInvalidHandleException()
     expected = win32api.FormatMessage(
         winerror.ERROR_INVALID_HANDLE).rstrip()
     self._testExceptionIndex(exc, 2, expected)
Esempio n. 21
0
def __StopServiceWithTimeout(hs, waitSecs=30):
    try:
        status = win32service.ControlService(hs,
                                             win32service.SERVICE_CONTROL_STOP)
    except pywintypes.error, exc:
        if exc.winerror != winerror.ERROR_SERVICE_NOT_ACTIVE:
            raise
    for i in range(waitSecs):
        status = win32service.QueryServiceStatus(hs)
        if status[1] == win32service.SERVICE_STOPPED:
            break
        win32api.Sleep(1000)
    else:
        raise pywintypes.error(
            winerror.ERROR_SERVICE_REQUEST_TIMEOUT, "ControlService",
            win32api.FormatMessage(
                winerror.ERROR_SERVICE_REQUEST_TIMEOUT)[:-2])


def StopServiceWithDeps(serviceName, machine=None, waitSecs=30):
    # Stop a service recursively looking for dependant services
    hscm = win32service.OpenSCManager(machine, None,
                                      win32service.SC_MANAGER_ALL_ACCESS)
    try:
        deps = __FindSvcDeps(serviceName)
        for dep in deps:
            hs = win32service.OpenService(hscm, dep,
                                          win32service.SERVICE_ALL_ACCESS)
            try:
                __StopServiceWithTimeout(hs, waitSecs)
            finally:
                win32service.CloseServiceHandle(hs)
Esempio n. 22
0
def main():
    parser = optparse.OptionParser(
        "%prog [options] auth|change ...",
        description="A win32net.NetValidatePasswordPolicy demo.",
    )

    parser.add_option(
        "-u",
        "--username",
        action="store",
        help="The username to pass to the function (only for the "
        "change command",
    )

    parser.add_option(
        "-p",
        "--password",
        action="store",
        help="The clear-text password to pass to the function "
        "(only for the 'change' command)",
    )

    parser.add_option(
        "-m",
        "--password-matched",
        action="store_false",
        default=True,
        help="Used to specify the password does NOT match (ie, "
        "uses False for the PasswordMatch/PasswordMatched "
        "arg, both 'auth' and 'change' commands)",
    )

    parser.add_option(
        "-s",
        "--server",
        action="store",
        help="The name of the server to execute the command on",
    )

    parser.add_option(
        "-f",
        "--show_fields",
        action="store_true",
        default=False,
        help="Print the NET_VALIDATE_PERSISTED_FIELDS returned",
    )

    options, args = parser.parse_args()

    if not args:
        args = ["auth"]

    for arg in args:
        if arg == "auth":
            input = {
                "PasswordMatched": options.password_matched,
            }
            val_type = win32netcon.NetValidateAuthentication
        elif arg == "change":
            input = {
                "ClearPassword": options.password,
                "PasswordMatch": options.password_matched,
                "UserAccountName": options.username,
            }
            val_type = win32netcon.NetValidatePasswordChange
        else:
            parser.error("Invalid arg - must be 'auth' or 'change'")

        try:
            fields, status = win32net.NetValidatePasswordPolicy(
                options.server, None, val_type, input)
        except NotImplementedError:
            print(
                "NetValidatePasswordPolicy not implemented on this platform.")
            return 1
        except win32net.error as exc:
            print("NetValidatePasswordPolicy failed: ", exc)
            return 1

        if options.show_fields:
            print("NET_VALIDATE_PERSISTED_FIELDS fields:")
            pprint(fields)

        print("Result of %r validation is %d: %s" %
              (arg, status, win32api.FormatMessage(status).strip()))

    return 0
Esempio n. 23
0
 def testMessageIndex(self):
     exc = self._getException()
     expected = win32api.FormatMessage(winerror.STG_E_INVALIDFLAG).rstrip()
     self._testExceptionIndex(exc, 1, expected)
Esempio n. 24
0
def putNoti(cmd, connectorList, notiKey, msg):

    global g_HWNDMAIN
    global g_OUT_FILE

    global g_RETRY_SENDFLAG
    global g_SEND_TIMEOUT

    if g_OUT_FILE:
        g_OUT_FILE.write(msg)
        g_OUT_FILE.flush()

    connectorLen = len(connectorList)

    idx = 0
    totalCon = 0

    #for connector in connectorList :
    while 1:

        totalCon += 1

        try:
            connector = connectorList[idx]
        except:
            __LOG__.Exception()

            # Loop Escape	-------------------------------------------
            __LOG__.Trace(
                "%-10s| SEND To client END ------------------" % ('INFO'),
                logging.INFO)
            break

        hwnd = connector.hWnd

        retMsg = 'NTI'   + DELIMETER_CLI + \
            str(hwnd)  + DELIMETER_CLI + \
            notiKey   + DELIMETER_CLI + \
            msg

        retA = 0
        retB = 0

        try:
            #retA, retB = win32gui.SendMessageTimeout(hwnd, win32con.WM_COPYDATA, 0, copy_struct, win32con.SMTO_NORMAL, g_SEND_TIMEOUT * 1000 ) # milisec

            retA, retB = sendMessage(hwnd, retMsg, g_SEND_TIMEOUT)
            __LOG__.Trace(
                "%-10s| SEND To client :ret:[%d:%d] [%d:%d/%d][%d] [%s]:[%s]" %
                ('INFO', retA, retB, idx, totalCon, connectorLen, hwnd, cmd,
                 retMsg), logging.INFO)

            idx = idx + 1

        except pywintypes.error:
            __LOG__.Exception()

            errno = sys.exc_info()[1][0]
            if errno == 1400:  ### ERROR_INVALID_WINDOW_HANDLE:
                #{
                __LOG__.Trace( "%-10s| Send To client : deregister hwd:[%s] [%d:%d/%d][%d:%s]: , ret[%d:%d], sendMessage:[%s] " % \
                    ('ERROR', hwnd, idx, totalCon, connectorLen, errno, win32api.FormatMessage(errno), retA, retB, retMsg), logging.ERROR )

                connector.deregister()

                # Delete send Message Self Handle
                if g_HWNDMAIN:
                    #{
                    retMsg = 'DEL'   + DELIMETER_CLI + \
                        str(hwnd)  + DELIMETER_CLI + \
                        notiKey   + DELIMETER_CLI + \
                        msg

                    #win32gui.SendMessageTimeout(g_HWNDMAIN, win32con.WM_COPYDATA, g_HWNDMAIN, copy_struct, win32con.SMTO_NORMAL, 1000 ) # milisec, 1 sec
                    retA, retB = sendMessage(g_HWNDMAIN, retMsg, 1000)
                #}
            #}
            else:
                #{
                __LOG__.Trace( "%-10s| Send To client: hwd:[%s] [%d:%d/%d][%d:%s]:, ret[%d:%d], sendMessage:[%s] " % \
                      ('ERROR', hwnd, idx, totalCon, connectorLen, errno, win32api.FormatMessage(errno), retA, retB, retMsg), logging.ERROR )

                # Loop Escape	-------------------------------------------
                if (connectorLen < totalCon):
                    __LOG__.Trace(
                        "%-10s| retry SEND To client END ------------------" %
                        ('INFO'), logging.INFO)
                    break

                #-------------------------------------------------------
                # if SendMessage  Failed, retry Flag : 07.09.28
                # retry 하지 않을경우 : list 의 index 를  next 로 증가하여 다음 connector 지정
                #-------------------------------------------------------
                if g_RETRY_SENDFLAG == False:
                    idx = idx + 1

                else:
                    continue
            #}
        except Exception, err:
            __LOG__.Exception()

        # Loop Escape	-------------------------------------------
        if (connectorLen <= totalCon):
            __LOG__.Trace(
                "%-10s| SEND To client END ------------------" % ('INFO'),
                logging.INFO)
            break
Esempio n. 25
0
def members(name, members_list, **kwargs):
    '''
    Ensure a group contains only the members in the list

    Args:

        name (str):
            The name of the group to modify

        members_list (str):
            A single user or a comma separated list of users. The group will
            contain only the users specified in this list.

    Returns:
        bool: ``True`` if successful, otherwise ``False``

    CLI Example:

    .. code-block:: bash

        salt '*' group.members foo 'user1,user2,user3'
    '''
    members_list = [
        salt.utils.win_functions.get_sam_name(m)
        for m in members_list.split(",")
    ]
    if not isinstance(members_list, list):
        log.debug('member_list is not a list')
        return False

    try:
        obj_group = _get_group_object(name)
    except pywintypes.com_error as exc:
        # Group probably doesn't exist, but we'll log the error
        msg = 'Failed to access group {0}. {1}'.format(
            name, win32api.FormatMessage(exc.excepinfo[5]))
        log.error(msg)
        return False

    existing_members = [_get_username(x) for x in obj_group.members()]
    existing_members.sort()
    members_list.sort()

    if existing_members == members_list:
        log.info('{0} membership is correct'.format(name))
        return True

    # add users
    success = True
    for member in members_list:
        if member not in existing_members:
            try:
                obj_group.Add('WinNT://' + member.replace('\\', '/'))
                log.info('User added: {0}'.format(member))
            except pywintypes.com_error as exc:
                msg = 'Failed to add {0} to {1}. {2}'.format(
                    member, name, win32api.FormatMessage(exc.excepinfo[5]))
                log.error(msg)
                success = False

    # remove users not in members_list
    for member in existing_members:
        if member not in members_list:
            try:
                obj_group.Remove('WinNT://' + member.replace('\\', '/'))
                log.info('User removed: {0}'.format(member))
            except pywintypes.com_error as exc:
                msg = 'Failed to remove {0} from {1}. {2}'.format(
                    member, name, win32api.FormatMessage(exc.excepinfo[5]))
                log.error(msg)
                success = False

    return success
Esempio n. 26
0
def unjoin_domain(username=None,
                  password=None,
                  domain=None,
                  workgroup='WORKGROUP',
                  disable=False,
                  restart=False):
    r'''
    Unjoin a computer from an Active Directory Domain. Requires a restart.

    Args:

        username (str):
            Username of an account which is authorized to manage computer
            accounts on the domain. Needs to be a fully qualified name like
            ``[email protected]`` or ``domain.tld\user``. If the domain is not
            specified, the passed domain will be used. If the computer account
            doesn't need to be disabled after the computer is unjoined, this can
            be ``None``.

        password (str):
            The password of the specified user

        domain (str):
            The domain from which to unjoin the computer. Can be ``None``

        workgroup (str):
            The workgroup to join the computer to. Default is ``WORKGROUP``

            .. versionadded:: 2015.8.2/2015.5.7

        disable (bool):
            ``True`` to disable the computer account in Active Directory.
            Default is ``False``

        restart (bool):
            ``True`` will restart the computer after successful unjoin. Default
            is ``False``

            .. versionadded:: 2015.8.2/2015.5.7

    Returns:
        dict: Returns a dictionary if successful, otherwise ``False``

    CLI Example:

    .. code-block:: bash

        salt 'minion-id' system.unjoin_domain restart=True

        salt 'minion-id' system.unjoin_domain username='******' \\
                         password='******' disable=True \\
                         restart=True
    '''
    if six.PY2:
        username = _to_unicode(username)
        password = _to_unicode(password)
        domain = _to_unicode(domain)

    status = get_domain_workgroup()
    if 'Workgroup' in status:
        if status['Workgroup'] == workgroup:
            return 'Already joined to {0}'.format(workgroup)

    if username and '\\' not in username and '@' not in username:
        if domain:
            username = '******'.format(username, domain)
        else:
            return 'Must specify domain if not supplied in username'

    if username and password is None:
        return 'Must specify a password if you pass a username'

    NETSETUP_ACCT_DELETE = 0x4  # pylint: disable=invalid-name

    unjoin_options = 0x0
    if disable:
        unjoin_options |= NETSETUP_ACCT_DELETE

    pythoncom.CoInitialize()
    conn = wmi.WMI()
    comp = conn.Win32_ComputerSystem()[0]
    err = comp.UnjoinDomainOrWorkgroup(Password=password,
                                       UserName=username,
                                       FUnjoinOptions=unjoin_options)

    # you have to do this because UnjoinDomainOrWorkgroup returns a
    # strangely formatted value that looks like (0,)
    if not err[0]:
        err = comp.JoinDomainOrWorkgroup(Name=workgroup)
        if not err[0]:
            ret = {'Workgroup': workgroup, 'Restart': False}
            if restart:
                ret['Restart'] = reboot()

            return ret
        else:
            log.error(win32api.FormatMessage(err[0]).rstrip())
            log.error('Failed to join the computer to {0}'.format(workgroup))
            return False
    else:
        log.error(win32api.FormatMessage(err[0]).rstrip())
        log.error('Failed to unjoin computer from {0}'.format(
            status['Domain']))
        return False
Esempio n. 27
0
def join_domain(domain,
                username=None,
                password=None,
                account_ou=None,
                account_exists=False,
                restart=False):
    '''
    Join a computer to an Active Directory domain. Requires a reboot.

    Args:

        domain (str):
            The domain to which the computer should be joined, e.g.
            ``example.com``

        username (str):
            Username of an account which is authorized to join computers to the
            specified domain. Needs to be either fully qualified like
            ``[email protected]`` or simply ``user``

        password (str):
            Password of the specified user

        account_ou (str):
            The DN of the OU below which the account for this computer should be
            created when joining the domain, e.g.
            ``ou=computers,ou=departm_432,dc=my-company,dc=com``

        account_exists (bool):
            If set to ``True`` the computer will only join the domain if the
            account already exists. If set to ``False`` the computer account
            will be created if it does not exist, otherwise it will use the
            existing account. Default is ``False``

        restart (bool):
            ``True`` will restart the computer after a successful join. Default
            is ``False``

            .. versionadded:: 2015.8.2/2015.5.7

    Returns:
        dict: Returns a dictionary if successful, otherwise ``False``

    CLI Example:

    .. code-block:: bash

        salt 'minion-id' system.join_domain domain='domain.tld' \\
                         username='******' password='******' \\
                         account_ou='ou=clients,ou=org,dc=domain,dc=tld' \\
                         account_exists=False, restart=True
    '''
    if six.PY2:
        domain = _to_unicode(domain)
        username = _to_unicode(username)
        password = _to_unicode(password)
        account_ou = _to_unicode(account_ou)

    status = get_domain_workgroup()
    if 'Domain' in status:
        if status['Domain'] == domain:
            return 'Already joined to {0}'.format(domain)

    if username and '\\' not in username and '@' not in username:
        username = '******'.format(username, domain)

    if username and password is None:
        return 'Must specify a password if you pass a username'

    # remove any escape characters
    if isinstance(account_ou, six.string_types):
        account_ou = account_ou.split('\\')
        account_ou = ''.join(account_ou)

    err = _join_domain(domain=domain,
                       username=username,
                       password=password,
                       account_ou=account_ou,
                       account_exists=account_exists)

    if not err:
        ret = {'Domain': domain, 'Restart': False}
        if restart:
            ret['Restart'] = reboot()
        return ret

    raise CommandExecutionError(win32api.FormatMessage(err).rstrip())
Esempio n. 28
0
def set_system_date_time(years=None,
                         months=None,
                         days=None,
                         hours=None,
                         minutes=None,
                         seconds=None):
    '''
    Set the system date and time. Each argument is an element of the date, but
    not required. If an element is not passed, the current system value for that
    element will be used. For example, if you don't pass the year, the current
    system year will be used. (Used by set_system_date and set_system_time)

    Args:

        years (int): Years digit, ie: 2015
        months (int): Months digit: 1 - 12
        days (int): Days digit: 1 - 31
        hours (int): Hours digit: 0 - 23
        minutes (int): Minutes digit: 0 - 59
        seconds (int): Seconds digit: 0 - 59

    Returns:
        bool: ``True`` if successful, otherwise ``False``

    CLI Example:

    .. code-block:: bash

        salt '*' system.set_system_date_ time 2015 5 12 11 37 53
    '''
    # Get the current date/time
    try:
        date_time = win32api.GetLocalTime()
    except win32api.error as exc:
        (number, context, message) = exc
        log.error('Failed to get local time')
        log.error('nbr: {0}'.format(number))
        log.error('ctx: {0}'.format(context))
        log.error('msg: {0}'.format(message))
        return False

    # Check for passed values. If not passed, use current values
    if years is None:
        years = date_time[0]
    if months is None:
        months = date_time[1]
    if days is None:
        days = date_time[3]
    if hours is None:
        hours = date_time[4]
    if minutes is None:
        minutes = date_time[5]
    if seconds is None:
        seconds = date_time[6]

    try:

        class SYSTEMTIME(ctypes.Structure):
            _fields_ = [('wYear', ctypes.c_int16), ('wMonth', ctypes.c_int16),
                        ('wDayOfWeek', ctypes.c_int16),
                        ('wDay', ctypes.c_int16), ('wHour', ctypes.c_int16),
                        ('wMinute', ctypes.c_int16),
                        ('wSecond', ctypes.c_int16),
                        ('wMilliseconds', ctypes.c_int16)]

        system_time = SYSTEMTIME()
        system_time.wYear = int(years)
        system_time.wMonth = int(months)
        system_time.wDay = int(days)
        system_time.wHour = int(hours)
        system_time.wMinute = int(minutes)
        system_time.wSecond = int(seconds)
        system_time_ptr = ctypes.pointer(system_time)
        succeeded = ctypes.windll.kernel32.SetLocalTime(system_time_ptr)
        if succeeded is not 0:
            return True
        else:
            log.error('Failed to set local time')
            raise CommandExecutionError(
                win32api.FormatMessage(succeeded).rstrip())
    except OSError as err:
        log.error('Failed to set local time')
        raise CommandExecutionError(err)
Esempio n. 29
0
 def _indicateError(self, ecode):
     raise RuntimeError('Error: %s' %
                        (win32api.FormatMessage(ecode).strip()))
Esempio n. 30
0
def getErrorMessage(res=0):
    # sys_fs_enc = sys.getfilesystemencoding() or 'mbcs'
    msg = win32api.FormatMessage(res)
    return msg.decode('windows-1250', 'ignore')