Exemple #1
0
def joinDomain(domain: str,
               ou: str,
               account: str,
               password: str,
               executeInOneStep: bool = False) -> None:
    '''
    Joins machine to a windows domain
    :param domain: Domain to join to
    :param ou: Ou that will hold machine
    :param account: Account used to join domain
    :param password: Password of account used to join domain
    :param executeInOneStep: If true, means that this machine has been renamed and wants to add NETSETUP_JOIN_WITH_NEW_NAME to request so we can do rename/join in one step.
    '''
    # If account do not have domain, include it
    if '@' not in account and '\\' not in account:
        if '.' in domain:
            account = account + '@' + domain
        else:
            account = domain + '\\' + account

    # Do log
    flags: typing.Any = NETSETUP_ACCT_CREATE | NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN

    if executeInOneStep:
        flags |= NETSETUP_JOIN_WITH_NEW_NAME

    flags = DWORD(flags)

    lpDomain = LPCWSTR(domain)

    # Must be in format "ou=.., ..., dc=...,"
    lpOu = LPCWSTR(ou) if ou is not None and ou != '' else None
    lpAccount = LPCWSTR(account)
    lpPassword = LPCWSTR(password)

    res = ctypes.windll.netapi32.NetJoinDomain(None, lpDomain, lpOu, lpAccount,
                                               lpPassword, flags)
    # Machine found in another ou, use it and warn this on log
    if res == 2224:
        flags = DWORD(NETSETUP_DOMAIN_JOIN_IF_JOINED | NETSETUP_JOIN_DOMAIN)
        res = ctypes.windll.netapi32.NetJoinDomain(None, lpDomain, None,
                                                   lpAccount, lpPassword,
                                                   flags)
    if res:
        # Log the error
        error = getErrorMessage(res)
        if res == 1355:
            error = "DC Is not reachable"
        logger.error('Error joining domain: {}, {}'.format(error, res))
        raise Exception(
            'Error joining domain {}, with credentials {}/*****{}: {}, {}'.
            format(domain, account,
                   ', under OU {}'.format(ou) if ou is not None else '', res,
                   error))
Exemple #2
0
def changeUserPassword(user, oldPassword, newPassword):
    computerName = LPCWSTR(getComputerName())
    user = LPCWSTR(user)
    oldPassword = LPCWSTR(oldPassword)
    newPassword = LPCWSTR(newPassword)

    res = ctypes.windll.netapi32.NetUserChangePassword(computerName, user, oldPassword, newPassword)

    if res != 0:
        # Log the error, and raise exception to parent
        error = getErrorMessage()
        raise Exception('Error changing password for user {}: {}'.format(user.value, error))
Exemple #3
0
def _volume_info_windows(path):
    # type: (str, ) -> _volumeinfotuple

    if not path.endswith("\\"):
        raise ValueError("X: usually doesn't work. X:\\ does.")

    RootPathName = LPCWSTR(path)
    VolumeNameBuffer = create_unicode_buffer(MAX_PATH + 1)
    VolumeNameSize = MAX_PATH + 1
    VolumeSerialNumber = DWORD()
    MaximumComponentLength = DWORD()
    FileSystemFlags = DWORD()
    FileSystemNameBuffer = create_unicode_buffer(MAX_PATH + 1)
    FileSystemNameSize = MAX_PATH + 1

    GetVolumeInformationW(
        RootPathName,
        VolumeNameBuffer,
        VolumeNameSize,
        byref(VolumeSerialNumber),
        byref(MaximumComponentLength),
        byref(FileSystemFlags),
        FileSystemNameBuffer,
        FileSystemNameSize,
    )

    return _volumeinfotuple(
        VolumeNameBuffer.value,
        VolumeSerialNumber.value,
        MaximumComponentLength.value,
        FileSystemFlags.value,
        FileSystemNameBuffer.value,
    )
Exemple #4
0
def msgbox(message):
    if sys.platform == 'win32':
        import ctypes
        from ctypes.wintypes import LPCWSTR
        ctypes.windll.user32.MessageBoxW(None, LPCWSTR(message),
                                         u"Kivy Fatal Error", 0)
        sys.exit(1)
Exemple #5
0
def send2trash(path):
    if not isinstance(path, text_type):
        path = text_type(path, 'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    # FIX: https://github.com/hsoft/send2trash/issues/17
    # Starting in python 3.6.3 it is no longer possible to use:
    # LPCWSTR(path + '\0') directly as embedded null characters are no longer
    # allowed in strings
    # Workaround 
    #  - create buffer of c_wchar[] (LPCWSTR is based on this type)
    #  - buffer is two c_wchar characters longer (double null terminator)
    #  - cast the address of the buffer to a LPCWSTR
    # NOTE: based on how python allocates memory for these types they should
    # always be zero, if this is ever not true we can go back to explicitly
    # setting the last two characters to null using buffer[index] = '\0'.
    buffer = create_unicode_buffer(path, len(path)+2)
    fileop.pFrom = LPCWSTR(addressof(buffer))
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        raise WindowsError(None, None, path, result)
Exemple #6
0
 def edit_item(self, item, logo, service, username, password, notes):
     target = LPCWSTR(repr((item.service, item.username)))
     self.advapi32.CredDeleteW(target, self.CRED_TYPE_GENERIC, 0)
     temp_item = self.create_item(logo, service, username, password, notes)
     self.collection.items.remove(temp_item)
     item.service = service
     item.username = username
 def __init__(self, dict):
     if not dict:
         self._as_parameter_ = None
     else:
         values = ["%s=%s" % (key, value) for (key, value) in dict.items()]
         values.append("")
         self._as_parameter_ = LPCWSTR("\0".join(values))
Exemple #8
0
def fop(files):
    import ctypes
    from ctypes.wintypes import HWND, UINT, LPCWSTR, BOOL

    class SHFILEOPSTRUCTW(ctypes.Structure):
        _fields_ = [
            ("hwnd", HWND),
            ("wFunc", UINT),
            ("pFrom", LPCWSTR),
            ("pTo", LPCWSTR),
            ("fFlags", ctypes.c_uint),
            ("fAnyOperationsAborted", BOOL),
            ("hNameMappings", ctypes.c_uint),
            ("lpszProgressTitle", LPCWSTR),
        ]

    SHFileOperationW = ctypes.windll.shell32.SHFileOperationW
    SHFileOperationW.argtypes = [ctypes.POINTER(SHFILEOPSTRUCTW)]
    pFrom = u'\x00'.join(files) + u'\x00'
    args = SHFILEOPSTRUCTW(wFunc=UINT(3),
                           pFrom=LPCWSTR(pFrom),
                           pTo=None,
                           fFlags=64,
                           fAnyOperationsAborted=BOOL())
    out = SHFileOperationW(ctypes.byref(args))
 def __init__(self, env):
     if not env:
         self._as_parameter_ = None
     else:
         values = []
         fs_encoding = sys.getfilesystemencoding() or 'mbcs'
         for k, v in list(env.items()):
             if isinstance(k, bytes):
                 k = k.decode(fs_encoding, 'replace')
             if isinstance(v, bytes):
                 v = v.decode(fs_encoding, 'replace')
             values.append("{}={}".format(k, v))
         values.append("")
         try:  # nekonbu72 +
             self._as_parameter_ = LPCWSTR("\0".join(values))
         except:  # nekonbu72 +
             self._as_parameter_ = LPCWSTR(None)  # nekonbu72 +
Exemple #10
0
def _connect(network, parameters):
    '''
    Attempts to connect to a specific network.
    '''
    global _dict  # pylint: disable=global-statement
    wireless_interface = _dict[network]

    wcp = WLAN_CONNECTION_PARAMETERS()
    connection_mode = parameters['connection_mode']
    wcp.wlanConnectionMode = WLAN_CONNECTION_MODE(connection_mode)

    if connection_mode == 0 or connection_mode == 1:
        wcp.strProfile = LPCWSTR(parameters["profile"])
    else:
        wcp.strProfile = None

    dot11Ssid = DOT11_SSID()
    try:
        dot11Ssid.SSID = parameters["ssid"]
        dot11Ssid.SSIDLength = len(parameters["ssid"])
    except KeyError:
        dot11Ssid.SSID = network
        dot11Ssid.SSIDLength = len(network)
    wcp.pDot11Ssid = pointer(dot11Ssid)

    dot11bssid = DOT11_BSSID_LIST()
    bssid = parameters["bssidList"]
    dot11bssid.Header = bssid['Header']
    dot11bssid.uNumOfEntries = bssid['uNumOfEntries']
    dot11bssid.uTotalNumOfEntries = bssid['uTotalNumOfEntries']
    dot11bssid.BSSIDs = bssid['BSSIDs']

    wcp.pDesiredBssidList = pointer(dot11bssid)

    bssType = parameters["bssType"]
    wcp.dot11BssType = DOT11_BSS_TYPE(bssType)

    wcp.dwFlags = DWORD(parameters["flags"])

    NegotiatedVersion = DWORD()
    ClientHandle = HANDLE()

    wlan = WlanOpenHandle(1, None, byref(NegotiatedVersion),
                          byref(ClientHandle))
    if wlan:
        sys_exit(FormatError(wlan))
    pInterfaceList = pointer(WLAN_INTERFACE_INFO_LIST())
    wlan = WlanEnumInterfaces(ClientHandle, None, byref(pInterfaceList))
    if wlan:
        sys_exit(FormatError(wlan))

    try:
        wlan = WlanConnect(ClientHandle, wireless_interface, wcp, None)
        if wlan:
            sys_exit(FormatError(wlan))
        WlanCloseHandle(ClientHandle, None)
    finally:
        WlanFreeMemory(pInterfaceList)
Exemple #11
0
def AskFolder(message=None,
              version=None,
              defaultLocation=None,
              location=None,
              windowTitle=None,
              actionButtonLabel=None,
              cancelButtonLabel=None,
              multiple=None):
    """Display a dialog asking the user for select a folder.
       modified to use unicode strings as much as possible
       returns unicode path
    """
    def BrowseCallback(hwnd, uMsg, lParam, lpData):
        if uMsg == BFFM_INITIALIZED:
            if actionButtonLabel:
                label = unicode(actionButtonLabel, errors='replace')
                user32.SendMessageW(hwnd, BFFM_SETOKTEXT, 0, label)
            if cancelButtonLabel:
                label = unicode(cancelButtonLabel, errors='replace')
                cancelButton = user32.GetDlgItem(hwnd, IDCANCEL)
                if cancelButton:
                    user32.SetWindowTextW(cancelButton, label)
            if windowTitle:
                title = unicode(windowTitle, erros='replace')
                user32.SetWindowTextW(hwnd, title)
            if defaultLocation:
                user32.SendMessageW(hwnd, BFFM_SETSELECTIONW, 1,
                                    defaultLocation.replace('/', '\\'))
            if location:
                x, y = location
                desktopRect = wintypes.RECT()
                user32.GetWindowRect(0, ctypes.byref(desktopRect))
                user32.SetWindowPos(hwnd, 0, desktopRect.left + x,
                                    desktopRect.top + y, 0, 0,
                                    SWP_NOACTIVATE | SWP_NOSIZE | SWP_NOZORDER)
            else:
                CenterWindow(hwnd)
        return 0

    # This next line is needed to prevent gc of the callback
    callback = BrowseCallbackProc(BrowseCallback)

    browseInfo = BROWSEINFO()
    browseInfo.pszDisplayName = ctypes.c_char_p('\0' * (MAX_PATH + 1))
    browseInfo.lpszTitle = message
    browseInfo.lpfn = callback

    pidl = shell32.SHBrowseForFolder(ctypes.byref(browseInfo))
    if not pidl:
        result = None
    else:
        path = LPCWSTR(u" " * (MAX_PATH + 1))
        shell32.SHGetPathFromIDListW(pidl, path)
        ole32.CoTaskMemFree(pidl)
        result = path.value
    return result
Exemple #12
0
def GetDiskFreeSpaceEx(lpDirectoryName):
    lp_dirname = LPCWSTR(lpDirectoryName)
    lpFreeBytesAvailable = c_ulonglong(0)
    lpTotalNumberOfBytes = c_ulonglong(0)
    lpTotalNumberOfFreeBytes = c_ulonglong(0)
    _BaseGetDiskFreeSpaceEx(lp_dirname, byreference(lpFreeBytesAvailable), byreference(lpTotalNumberOfBytes), byreference(lpTotalNumberOfFreeBytes))
    freeBytesAvailable = lpFreeBytesAvailable.value
    totalNumberOfBytes = lpTotalNumberOfBytes.value
    totalNumberOfFreeBytes = lpTotalNumberOfFreeBytes.value
    return (freeBytesAvailable, totalNumberOfBytes, totalNumberOfFreeBytes)
Exemple #13
0
def PrjGetOnDiskFileState(path: Path) -> PRJ_FILE_STATE:
    state = ctypes.c_int(0)
    result = _PrjGetOnDiskFileState(LPCWSTR(str(path)), ctypes.byref(state))

    # Python will automatically throw OSError when result is non-zero
    if result == 0:
        return PRJ_FILE_STATE(state.value)

    # It should never reach here, but just to make typechecker happy
    raise RuntimeError("Windows Error: " + result)
Exemple #14
0
def renameComputer(newName):
    # Needs admin privileges to work
    if ctypes.windll.kernel32.SetComputerNameExW(
            DWORD(win32con.ComputerNamePhysicalDnsHostname),
            LPCWSTR(newName)) == 0:  # @UndefinedVariable
        # win32api.FormatMessage -> returns error string
        # win32api.GetLastError -> returns error code
        # (just put this comment here to remember to log this when logger is available)
        error = getErrorMessage()
        computerName = win32api.GetComputerNameEx(
            win32con.ComputerNamePhysicalDnsHostname)
        raise Exception('Error renaming computer from {} to {}: {}'.format(
            computerName, newName, error))
Exemple #15
0
def GetLocaleInfoEx(lp_locale_name, lc_type):
    if not isinstance(lc_type, LCTYPE):
        lc_type = LCTYPE(lc_type)

    lp_lc_data = (ctypes.c_wchar * 0)()

    cch_data = _GetLocaleInfoEx(
        LPCWSTR(lp_locale_name),
        lc_type,
        lp_lc_data,
        0
    )
    if cch_data == 0:
        return ''

    lp_lc_data = (ctypes.c_wchar * cch_data)()
    res = _GetLocaleInfoEx(
        LPCWSTR(lp_locale_name),
        lc_type,
        lp_lc_data,
        cch_data
    )

    if res == 0:
        raise ctypes.WinError()

    output = ''
    for i in range(res):
        char = lp_lc_data[i]
        if char in ('\x00', 0x0):
            break

        output += char

    try:
        return int(output)
    except ValueError:
        return output
Exemple #16
0
def _disk_usage_windows(path):
    # type: (str, ) -> _usagetuple

    DirectoryName = LPCWSTR(path)
    FreeBytesAvailableToCaller = ULARGE_INTEGER(0)  # user free
    TotalNumberOfBytes = ULARGE_INTEGER(0)  # user total
    TotalNumberOfFreeBytes = None  # total free

    GetDiskFreeSpaceExW(DirectoryName, byref(FreeBytesAvailableToCaller),
                        byref(TotalNumberOfBytes), TotalNumberOfFreeBytes)
    return _usagetuple(
        TotalNumberOfBytes.value,
        TotalNumberOfBytes.value - FreeBytesAvailableToCaller.value,
        FreeBytesAvailableToCaller.value)
 def __init__(self, dict):
     if not dict:
         self._as_parameter_ = None
     else:
         if version_info >= (3, 0):
             # on python3 LPCWSTR("\0") errors with 'ValueError: embedded null character'
             # TODO(python3): find a proper fix for that
             self._as_parameter_ = None
         else:
             values = [
                 "%s=%s" % (key, value) for (key, value) in dict.items()
             ]
             values.append("")
             self._as_parameter_ = LPCWSTR("\0".join(values))
Exemple #18
0
def send2trash(path):
    if not isinstance(path, text_type):
        path = text_type(path, 'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    fileop.pFrom = LPCWSTR(path + '\0')
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        raise WindowsError(None, None, path, result)
Exemple #19
0
def send2trash(paths):
    if not isinstance(paths, list):
        paths = [paths]
    # convert data type
    paths = [
        text_type(path, "mbcs") if not isinstance(path, text_type) else path
        for path in paths
    ]
    # convert to full paths
    paths = [
        op.abspath(path) if not op.isabs(path) else path for path in paths
    ]
    # get short path to handle path length issues
    paths = [get_short_path_name(path) for path in paths]
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    # FIX: https://github.com/hsoft/send2trash/issues/17
    # Starting in python 3.6.3 it is no longer possible to use:
    # LPCWSTR(path + '\0') directly as embedded null characters are no longer
    # allowed in strings
    # Workaround
    #  - create buffer of c_wchar[] (LPCWSTR is based on this type)
    #  - buffer is two c_wchar characters longer (double null terminator)
    #  - cast the address of the buffer to a LPCWSTR
    # NOTE: based on how python allocates memory for these types they should
    # always be zero, if this is ever not true we can go back to explicitly
    # setting the last two characters to null using buffer[index] = '\0'.
    # Additional note on another issue here, unicode_buffer expects length in
    # bytes essentially, so having multi-byte characters causes issues if just
    # passing pythons string length.  Instead of dealing with this difference we
    # just create a buffer then a new one with an extra null.  Since the non-length
    # specified version apparently stops after the first null, join with a space first.
    buffer = create_unicode_buffer(" ".join(paths))
    # convert to a single string of null terminated paths
    path_string = "\0".join(paths)
    buffer = create_unicode_buffer(path_string, len(buffer) + 1)
    fileop.pFrom = LPCWSTR(addressof(buffer))
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        raise WindowsError(result, FormatError(result), paths)
Exemple #20
0
def main(pid=None):
    PROCESS_TERMINATE = 0x0001
    PROCESS_QUERY_INFORMATION = 0x0400
    JOB_OBJECT_ALL_ACCESS = 0x1F001F
    hProc = HANDLE()
    result = BOOL()
    kernel32 = windll.kernel32
    hProc = kernel32.OpenProcess(PROCESS_TERMINATE | PROCESS_QUERY_INFORMATION,
                                 None, pid)
    hJobObject = kernel32.OpenJobObjectW(JOB_OBJECT_ALL_ACCESS, 1,
                                         LPCWSTR("fuzzjob"))
    if hJobObject == None:
        # this process is not in the fuzzjob, bail
        exit()
    kernel32.IsProcessInJob(hProc, hJobObject, byref(result))
    if result.value:
        kernel32.TerminateJobObject(hJobObject, 0xC0000005)
Exemple #21
0
def send2trash(path):
    if not isinstance(path, unicode):
        path = unicode(path, u'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    fileop.pFrom = LPCWSTR(path + u'\0')
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        msg = u"Couldn't perform operation. Error code: %d" % result
        raise OSError(msg)
Exemple #22
0
def send2trash(path):
    opath = path
    if not isinstance(path, unicode):
        path = unicode(path, u'mbcs')
    if not op.isabs(path):
        path = op.abspath(path)
    fileop = SHFILEOPSTRUCTW()
    fileop.hwnd = 0
    fileop.wFunc = FO_DELETE
    fileop.pFrom = LPCWSTR(path + u'\0')
    fileop.pTo = None
    fileop.fFlags = FOF_ALLOWUNDO | FOF_NOCONFIRMATION | FOF_NOERRORUI | FOF_SILENT
    fileop.fAnyOperationsAborted = 0
    fileop.hNameMappings = 0
    fileop.lpszProgressTitle = None
    result = SHFileOperationW(byref(fileop))
    if result:
        # user's system is broken, just delete
        os.unlink(opath)
def _UpdateResource(hUpdate, lpType, lpName, wLanguage, lpData, cbData):
    lp_type = LPCWSTR(lpType)
    lp_name = LPCWSTR(lpName)
    _BaseUpdateResource(hUpdate, lp_type, lp_name, wLanguage, lpData, cbData)
Exemple #24
0
def is_hidden(path):
    """File is hidden."""
    return _GetFileAttributesW(LPCWSTR(path)) & _FILE_ATTRIBUTE_HIDDEN
def GetFileAttributes(lpFileName):
    lp_filename = LPCWSTR(lpFileName)
    return _BaseGetFileAttributes(lp_filename)
def _EnumResourceNames(hModule, lpszType, lpEnumFunc, lParam):
    resource_type = LPCWSTR(lpszType)
    _BaseEnumResourceNames(hModule, resource_type, lpEnumFunc, lParam)
def _EnumResourceLanguages(hModule, lpType, lpName, lpEnumFunc, lParam):
    resource_type = LPCWSTR(lpType)
    resource_name = LPCWSTR(lpName)
    _BaseEnumResourceLanguages(hModule, resource_type, resource_name,
                               lpEnumFunc, lParam)
Exemple #28
0
 def get_cred(self):
     target = LPCWSTR(repr((self.service, self.username)))
     pcred = ctypes.pointer(Credential())
     self.advapi32.CredReadW(target, self.CRED_TYPE_GENERIC, 0,
                             ctypes.byref(pcred))
     return pcred.contents
Exemple #29
0
 def delete_item(self, item):
     target = LPCWSTR(repr((item.service, item.username)))
     self.advapi32.CredDeleteW(target, self.CRED_TYPE_GENERIC, 0)
     self.collection.items.remove(item)
def _FindResourceEx(hModule, lpType, lpName, wLanguage):
    resource_type = LPCWSTR(lpType)
    resource_name = LPCWSTR(lpName)
    return _BaseFindResourceEx(hModule, resource_type, resource_name,
                               wLanguage)