Пример #1
0
    def CreatePipeSecurityObject(self):
        # Create a security object giving World read/write access,
        # but only "Owner" modify access.
        sa = pywintypes.SECURITY_ATTRIBUTES()
        sidEveryone = pywintypes.SID()
        sidEveryone.Initialize(SECURITY_WORLD_SID_AUTHORITY, 1)
        sidEveryone.SetSubAuthority(0, SECURITY_WORLD_RID)

        #sidLocalAdministrator = pywintypes.SID()
        #sidLocalAdministrator.Initialize(SECURITY_NT_AUTHORITY,2)
        #sidLocalAdministrator.SetSubAuthority(0, SECURITY_BUILTIN_DOMAIN_RID)
        #sidLocalAdministrator.SetSubAuthority(1, DOMAIN_ALIAS_RID_ADMINS)

        sidCreator = pywintypes.SID()
        sidCreator.Initialize(SECURITY_CREATOR_SID_AUTHORITY, 1)
        sidCreator.SetSubAuthority(0, SECURITY_CREATOR_OWNER_RID)

        acl = pywintypes.ACL()
        acl.AddAccessAllowedAce(FILE_GENERIC_READ | FILE_GENERIC_WRITE,
                                sidEveryone)
        #acl.AddAccessAllowedAce(FILE_GENERIC_READ|FILE_GENERIC_WRITE, sidLocalAdministrator)
        acl.AddAccessAllowedAce(FILE_ALL_ACCESS, sidCreator)

        sa.SetSecurityDescriptorDacl(1, acl, 0)
        return sa
Пример #2
0
def create_desktop(desktop_name, start_explorer=1):
    """ Creates a new desktop and spawns a thread running on it
        Will also start a new icon thread on an existing desktop
    """
    sa = pywintypes.SECURITY_ATTRIBUTES()
    sa.bInheritHandle = 1

    try:
        hdesk = win32service.CreateDesktop(desktop_name, 0,
                                           win32con.MAXIMUM_ALLOWED, sa)
    except win32service.error:
        traceback.print_exc()
        errbuf = cStringIO.StringIO()
        traceback.print_exc(None, errbuf)
        win32api.MessageBox(0, errbuf.getvalue(), 'Desktop creation failed')
        return
    if start_explorer:
        s = win32process.STARTUPINFO()
        s.lpDesktop = desktop_name
        prc_info = win32process.CreateProcess(None, "Explorer.exe", None, None,
                                              True,
                                              win32con.CREATE_NEW_CONSOLE,
                                              None, 'c:\\', s)

    th = thread.start_new_thread(new_icon, (hdesk, desktop_name))
    hdesk.SwitchDesktop()
Пример #3
0
    def __init__(self, path):
        self.hInRead = None
        self.hInWrite = None
        self.hOutRead = None
        self.hOutWrite = None
        sa = pywintypes.SECURITY_ATTRIBUTES()
        sa.SetSecurityDescriptorDacl(1, None, 0)

        self.hInRead, self.hInWrite = win32pipe.CreatePipe(sa, 0)
        self.hOutRead, self.hOutWrite = win32pipe.CreatePipe(sa, 0)

        si = win32process.STARTUPINFO()
        si.dwFlags = win32con.STARTF_USESTDHANDLES | \
                           win32process.STARTF_USESHOWWINDOW
        si.hStdError = self.hOutWrite
        si.hStdOutput = self.hOutWrite
        si.hStdInput = self.hInRead
        si.wShowWindow = win32con.SW_HIDE

        create_flags = win32process.CREATE_NEW_CONSOLE
        self.info = win32process.CreateProcess(None, path, None, None, \
         True, create_flags, None, None, si)

        if self.info[0]:
            print('create process success')
Пример #4
0
def file_is_locked(path_to_file):
    """
    Return True if file is locked

    NOTE: Windows only.
    """
    if os.name != 'nt':  # just in case
        return

    if not HAS_PYWIN32:
        return

    secur_att = pywintypes.SECURITY_ATTRIBUTES()
    secur_att.Initialize()

    try:
        # try make a handle for READING the file
        hfile = win32file.CreateFile(
            path_to_file,  # path to file
            win32con.GENERIC_READ,  # open for reading
            0,  # do not share with other proc
            secur_att,
            win32con.OPEN_EXISTING,  # existing file only
            win32con.FILE_ATTRIBUTE_NORMAL,  # normal file
            0  # no attr. template
        )
    except pywintypes.error:
        return True
    else:  # in case all went ok, close file handle (go to hell WinAPI)
        hfile.Close()
        return False
Пример #5
0
 def create(cls,
            name,
            path='',
            host=PIPE_LOCALHOST,
            blocking=True,
            msgLimit=0,
            logger=logging.getLogger("k_os.ipc"),
            level=logging.INFO):
     pname = cls.getCanoicalName(host, path, name)
     sa = pywintypes.SECURITY_ATTRIBUTES()
     instance = cls(logger, level)
     blockingMode = win32pipe.PIPE_WAIT if blocking else win32pipe.PIPE_NOWAIT
     pmode = win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | blockingMode
     instance.name = name
     instance.handle = win32pipe.CreateNamedPipe(
         pname, win32pipe.PIPE_ACCESS_DUPLEX, pmode,
         win32pipe.PIPE_UNLIMITED_INSTANCES, 100, 100,
         win32pipe.NMPWAIT_USE_DEFAULT_WAIT, sa)
     NamedPipeServer.numberOfInstances += 1
     instance._logger.debug("Created NamedPipe '%s'." % pname)
     instance._logger.debug("Current # of instances = %u." %
                            NamedPipeServer.numberOfInstances)
     res = win32pipe.ConnectNamedPipe(instance.handle, None)
     instance._logger.debug("Client connected to NamedPipe.")
     return instance
def run_pywin32_hidden(cmd_line, cwd=None):
    import win32con
    import pywintypes
    import win32service
    import win32process
    import win32event

    # Open Desktop. No need to close as destroyed when process ends
    desktop_name = "pystatacons"
    try:
        _ = win32service.OpenDesktop(desktop_name, 0, True, win32con.MAXIMUM_ALLOWED)
    except win32service.error:  # desktop doesn't exist
        try:
            sa = pywintypes.SECURITY_ATTRIBUTES()
            sa.bInheritHandle = 1
            _ = win32service.CreateDesktop(desktop_name, 0, win32con.MAXIMUM_ALLOWED, sa)  # return if already created
        except win32service.error:
            sfi.SFIToolkit.display("Couldn't create Desktop.")
            sfi.SFIToolkit.pollnow()
            return 1337

    s = win32process.STARTUPINFO()
    s.lpDesktop = desktop_name
    s.dwFlags = win32con.STARTF_USESHOWWINDOW + win32con.STARTF_FORCEOFFFEEDBACK
    s.wShowWindow = win32con.SW_SHOWMINNOACTIVE
    proc_ret = win32process.CreateProcess(None, cmd_line, None, None, False, 0, None, cwd, s)
    #proc_ret = win32process.CreateProcess(r"C:\Windows\System32\cmd.exe", cmd_line, None, None, False, 0, None, cwd, s)
    # hProcess, _, dwProcessId, _
    sfi.SFIToolkit.display(cmd_line + "." + "\n" + "Starting in hidden desktop (pid=" + str(proc_ret[2]) + ").")
    sfi.SFIToolkit.pollnow()
    win32event.WaitForSingleObject(proc_ret[0], win32event.INFINITE)
    ret_code = win32process.GetExitCodeProcess(proc_ret[0])
    return ret_code
Пример #7
0
    def SvcDoRun(self):
        # We create our named pipe.
        pipeName = "\\\\.\\pipe\\PyPipeService"
        openMode = win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_OVERLAPPED
        pipeMode = win32pipe.PIPE_TYPE_MESSAGE

        # When running as a service, we must use special security for the pipe
        sa = pywintypes.SECURITY_ATTRIBUTES()
        # Say we do have a DACL, and it is empty
        # (ie, allow full access!)
        sa.SetSecurityDescriptorDacl(1, None, 0)

        pipeHandle = win32pipe.CreateNamedPipe(
            pipeName,
            openMode,
            pipeMode,
            win32pipe.PIPE_UNLIMITED_INSTANCES,
            0,
            0,
            6000,  # default buffers, and 6 second timeout.
            sa)

        # Loop accepting and processing connections
        while 1:
            try:
                hr = win32pipe.ConnectNamedPipe(pipeHandle, self.overlapped)
            except error, details:
                print "Error connecting pipe!", details
                pipeHandle.Close()
                break

            if hr == winerror.ERROR_PIPE_CONNECTED:
                # Client is fast, and already connected - signal event
                win32event.SetEvent(self.overlapped.hEvent)
            # Wait for either a connection, or a service stop request.
            timeout = win32event.INFINITE
            waitHandles = self.hWaitStop, self.overlapped.hEvent
            rc = win32event.WaitForMultipleObjects(waitHandles, 0, timeout)
            if rc == win32event.WAIT_OBJECT_0:
                # Stop event
                break
            else:
                # Pipe event - read the data, and write it back.
                # (We only handle a max of 255 characters for this sample)
                try:
                    hr, data = win32file.ReadFile(pipeHandle, 256)
                    win32file.WriteFile(pipeHandle, "You sent me:" + data)
                    # And disconnect from the client.
                    win32pipe.DisconnectNamedPipe(pipeHandle)
                except win32file.error:
                    # Client disconnected without sending data
                    # or before reading the response.
                    # Thats OK - just get the next connection
                    continue
Пример #8
0
def NullFile(inheritable):
  """Create a null file handle."""
  if inheritable:
    sa = pywintypes.SECURITY_ATTRIBUTES()
    sa.bInheritHandle = 1
  else:
    sa = None

  return win32file.CreateFile("nul",
    win32file.GENERIC_READ | win32file.GENERIC_WRITE,
    win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE,
    sa, win32file.OPEN_EXISTING, 0, None)
Пример #9
0
 def create(cls,
            name,
            path='',
            host=MS_LOCALHOST,
            blocking=True,
            msgLimit=0):
     name = cls.getCanoicalName(host, path, name)
     sa = pywintypes.SECURITY_ATTRIBUTES()
     instance = cls()
     instance.name = name
     instance.handle = win32file.CreateMailslot(
         name, msgLimit, blocking and MAILSLOT_WAIT_FOREVER or 0, sa)
     return instance
Пример #10
0
    def startPipeServer(self, event, wait_time=0):
        openMode = win32pipe.PIPE_ACCESS_DUPLEX
        pipeMode = win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT

        sa = pywintypes.SECURITY_ATTRIBUTES()
        sa.SetSecurityDescriptorDacl(1, None, 0)

        pipe_handle = win32pipe.CreateNamedPipe(
            self.pipename, openMode, pipeMode,
            win32pipe.PIPE_UNLIMITED_INSTANCES, 0, 0, 2000, sa)

        threading.Thread(target=self._serverThread,
                         args=(pipe_handle, event, wait_time)).start()
Пример #11
0
 def open(cls, name, path='', host='.'):
     sa = pywintypes.SECURITY_ATTRIBUTES()
     name = cls.getCanoicalName(host, path, name)
     instance = cls()
     instance.name = name
     try:
         instance.handle = win32file.CreateFile(
             name, win32file.GENERIC_WRITE | win32file.GENERIC_WRITE,
             win32file.FILE_SHARE_READ | win32file.FILE_SHARE_WRITE, sa,
             win32con.OPEN_ALWAYS, 0, None)
     except pywintypes.error as exc:
         if exc.args[0] == ERROR_FILE_NOT_FOUND:
             raise RuntimeError("Server for %s '%s' not started." %
                                (cls.objType, name))
     self._opened = True
     return instance
Пример #12
0
def createEventSecurityObject():
    # Create a security object giving World read/write access,
    # but only "Owner" modify access.
    sa = pywintypes.SECURITY_ATTRIBUTES()
    sidEveryone = pywintypes.SID()
    sidEveryone.Initialize(ntsecuritycon.SECURITY_WORLD_SID_AUTHORITY, 1)
    sidEveryone.SetSubAuthority(0, ntsecuritycon.SECURITY_WORLD_RID)
    sidCreator = pywintypes.SID()
    sidCreator.Initialize(ntsecuritycon.SECURITY_CREATOR_SID_AUTHORITY, 1)
    sidCreator.SetSubAuthority(0, ntsecuritycon.SECURITY_CREATOR_OWNER_RID)

    acl = pywintypes.ACL()
    acl.AddAccessAllowedAce(win32event.EVENT_MODIFY_STATE, sidEveryone)
    acl.AddAccessAllowedAce(ntsecuritycon.FILE_ALL_ACCESS, sidCreator)

    sa.SetSecurityDescriptorDacl(1, acl, 0)
    return sa
Пример #13
0
 def Open(self):
     pipeName = r"\\%s\pipe\%s" % (self.serverName or ".", self.name)
     if self.asServer:
         cx_Logging.Info("Creating pipe (as server): %s", self.name)
         sa = pywintypes.SECURITY_ATTRIBUTES()
         sa.SetSecurityDescriptorDacl(1, None, 0)
         self.handle = win32pipe.CreateNamedPipe(
             pipeName, win32pipe.PIPE_ACCESS_DUPLEX,
             win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT,
             self.maxInstances, self.maxSize, self.maxSize, self.timeout,
             sa)
         win32pipe.ConnectNamedPipe(self.handle)
     else:
         cx_Logging.Info("Connecting to pipe (as client): %s on %s",
                         self.name, self.serverName or ".")
         self.handle = win32file.CreateFile(
             pipeName, win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0,
             None, win32file.OPEN_EXISTING, 0, None)
Пример #14
0
    def create_named_pipe(self):
        openMode = win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_OVERLAPPED
        pipeMode = win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE

        saAttr = pywintypes.SECURITY_ATTRIBUTES()
        saAttr.SetSecurityDescriptorDacl(1, None, 0)

        self._handle = win32pipe.CreateNamedPipe(
            self._pipe_name, openMode, pipeMode,
            win32pipe.PIPE_UNLIMITED_INSTANCES, self._buff_size,
            self._buff_size, win32pipe.NMPWAIT_WAIT_FOREVER, saAttr)

        err = win32api.GetLastError()
        if self._handle.handle == winerror.ERROR_INVALID_HANDLE:
            raise TTransportException(
                type=TTransportException.NOT_OPEN,
                message='Tcreate_named_pipe failed: {}'.format(err))
        return True
Пример #15
0
def create_pipe(pipe_name):
    pipe_path = f"\\\\.\\pipe\\{pipe_name}"

    security_attributes = pywintypes.SECURITY_ATTRIBUTES()

    out_buf_sz = 64 * 1024
    in_buf_sz = 64 * 1024
    def_timeout = 0

    #  the second parameter "pDacl", if it is NULL, a NULL DACL is assigned to the security descriptor, which allows all access to the object
    security_attributes.SetSecurityDescriptorDacl(1, None, 1)
    pipe = win32pipe.CreateNamedPipe(
        pipe_path, win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE
        | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT,
        win32pipe.PIPE_UNLIMITED_INSTANCES, out_buf_sz, in_buf_sz, def_timeout,
        security_attributes)

    return pipe
Пример #16
0
def mkfifo(name):
    openMode = win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_OVERLAPPED
    #openMode = win32pipe.PIPE_ACCESS_INBOUND | win32file.FILE_FLAG_OVERLAPPED
    pipeMode = win32pipe.PIPE_TYPE_BYTE | win32pipe.PIPE_READMODE_BYTE
    #        | win32pipe.PIPE_NOWAIT
    fileName = PIPE_PREFIX % name
    fileName = fileName.replace("\\", "/")
    fileName = fileName.replace(":", "_")
    sa = pywintypes.SECURITY_ATTRIBUTES()
    sa.SetSecurityDescriptorDacl(1, None, 0)
    #for i in range(0,1):
    pipe_handle = win32pipe.CreateNamedPipe(
        fileName, openMode, pipeMode, 10, 65536, 65536, 300, None
        #win32pipe.PIPE_UNLIMITED_INSTANCES,
        #200,
        #0,
        #0,
        #2000,
        #sa
    )
    PIPE_HANDLES[name] = pipe_handle
Пример #17
0
        def __init__(self, sDevice, sMode):
            oSecurityAttributes = pywintypes.SECURITY_ATTRIBUTES()
            oSecurityAttributes.bInheritHandle = 1
            try:
                sDevice = '\\\\.\\' + sDevice
                self._oFd = win32file.CreateFile(
                    sDevice, win32con.GENERIC_READ | win32con.GENERIC_WRITE, 0,
                    oSecurityAttributes, win32con.OPEN_EXISTING,
                    win32file.FILE_FLAG_OVERLAPPED, 0)
            except:
                print('Failed to open COM port' + sDevice)
                self._oFd = 0
                return

            win32file.SetCommMask(self._oFd, win32file.EV_RXCHAR)
            win32file.SetupComm(self._oFd, 4096, 4096)
            win32file.PurgeComm(
                self._oFd, win32file.PURGE_TXABORT | win32file.PURGE_RXABORT
                | win32file.PURGE_TXCLEAR | win32file.PURGE_RXCLEAR)
            tCommTimeouts = (1000, 2, 2000, 2, 1000)
            win32file.SetCommTimeouts(self._oFd, tCommTimeouts)
            cCommDeviceBase.__init__(self, sDevice, sMode)
Пример #18
0
    def _CreatePipe(self):
        """Return a new pipe.

        returns -- A tuple (under UNIX) or list (under Windows)
        consisting of the file descriptors (UNIX) or handles (Windows)
        for the read end and write end of a new pipe.  The pipe is
        inheritable by child processes.  On UNIX the fds will not be
        inherited across 'exec'."""

        if sys.platform == "win32":
            # Create a security descriptor so that we can mark the handles
            # as inheritable.  (A call to os.pipe under Windows
            # returns handles that are not inheritable.)
            sa = pywintypes.SECURITY_ATTRIBUTES()
            sa.bInheritHandle = 1
            # Transform the tuple returned into a list so that the
            # individual elements can be altered.
            r, w = win32pipe.CreatePipe(sa, 0)
            return [r, w]
        else:
            pipe = os.pipe()
            for fd in pipe:
                qm.common.close_file_on_exec(fd)
            return pipe
Пример #19
0
def file_is_locked(path_to_file):
    '''returns True if file is locked (WINDOWS ONLY)'''
    if os.name != 'nt':  # just in case
        return

    if not HAS_PYWIN32:
        return

    secur_att = pywintypes.SECURITY_ATTRIBUTES()
    secur_att.Initialize()

    try:
        # try make a handle for READING the file
        hfile = win32file.CreateFile(
            path_to_file,  # path to file
            win32con.GENERIC_READ,  # open for reading
            0,  # do not share with other proc
            secur_att,
            win32con.OPEN_EXISTING,  # existing file only
            win32con.FILE_ATTRIBUTE_NORMAL,  # normal file
            0  # no attr. template
        )
    except pywintypes.error, e:
        return True
Пример #20
0
                                     os.path.join(root, filename))
            files_copied += 1
        except pywintypes.error as err:
            if err.winerror != 183:  #pywintypes.error (183, 'CreateHardLink', 'Cannot create a file when that file already exists.')
                raise
    for exclude in ('.git', '.svn', 'CVS', '.hg', '3rdParty', 'Python27',
                    'Python26'):
        if exclude in dirs:
            dirs.remove(exclude)

print "%d files copied" % files_copied

startup = win32process.STARTUPINFO()
startup.dwFlags += win32process.STARTF_USESTDHANDLES
startup.hStdInput = win32file.INVALID_HANDLE_VALUE
security_attributes = pywintypes.SECURITY_ATTRIBUTES()
security_attributes.bInheritHandle = 1
startup.hStdOutput = startup.hStdError = win32file.CreateFile(
    os.path.join(destdir,
                 "log"), win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ,
    security_attributes, win32file.CREATE_ALWAYS, 0, None)
win32file.WriteFile(startup.hStdOutput, 'log started\n')

(hProcess, hThread, processId, threadId) = win32process.CreateProcess(
    r"C:\Program Files (x86)\Debugging Tools for Windows (x86)\symstore.exe",
    "symstore.exe add /r /f \"%s\" /s C:\\symstore /t META" % destdir, None,
    None, True, win32process.CREATE_BREAKAWAY_FROM_JOB, None, None, startup)
win32api.CloseHandle(startup.hStdOutput)
win32api.CloseHandle(hThread)

# Don't need to wait here, but it doesn't take long, and we can remove the temp dir
Пример #21
0
    def __init__(self, cmd, mode='t', cwd=None, env=None, avatar=None):
        log.info("Process.__init__(cmd=%r, mode=%r, cwd=%r, env=%r)", cmd,
                 mode, cwd, env)
        # Keep a reference to ensure it is around for this object's destruction.
        self.__log = log
        self.mCmd = cmd
        self.mCwd = cwd
        self.mEnv = env
        self.mAvatar = avatar
        self.mMode = mode
        if self.mMode not in ('t', 'b'):
            raise ProcessError("'mode' must be 't' or 'b'.")
        self.mClosed = False

        si = win32process.STARTUPINFO()
        si.dwFlags = (win32con.STARTF_USESTDHANDLES
                      ^ win32con.STARTF_USESHOWWINDOW)

        # Create pipes for std handles.
        # (Set the bInheritHandle flag so pipe handles are inherited.)
        saAttr = pywintypes.SECURITY_ATTRIBUTES()
        saAttr.bInheritHandle = 1
        #XXX Should maybe try with os.pipe. Dunno what that does for
        #    inheritability though.
        hChildStdinRd, hChildStdinWr = win32pipe.CreatePipe(saAttr, 0)
        hChildStdoutRd, hChildStdoutWr = win32pipe.CreatePipe(saAttr, 0)
        hChildStderrRd, hChildStderrWr = win32pipe.CreatePipe(saAttr, 0)

        try:
            # Duplicate the parent ends of the pipes so they are not
            # inherited.
            hChildStdinWrDup = win32api.DuplicateHandle(
                win32api.GetCurrentProcess(),
                hChildStdinWr,
                win32api.GetCurrentProcess(),
                0,
                0,  # not inherited
                DUPLICATE_SAME_ACCESS)
            win32api.CloseHandle(hChildStdinWr)
            self._hChildStdinWr = hChildStdinWrDup
            hChildStdoutRdDup = win32api.DuplicateHandle(
                win32api.GetCurrentProcess(),
                hChildStdoutRd,
                win32api.GetCurrentProcess(),
                0,
                0,  # not inherited
                DUPLICATE_SAME_ACCESS)
            win32api.CloseHandle(hChildStdoutRd)
            self._hChildStdoutRd = hChildStdoutRdDup
            hChildStderrRdDup = win32api.DuplicateHandle(
                win32api.GetCurrentProcess(),
                hChildStderrRd,
                win32api.GetCurrentProcess(),
                0,
                0,  # not inherited
                DUPLICATE_SAME_ACCESS)
            win32api.CloseHandle(hChildStderrRd)
            self._hChildStderrRd = hChildStderrRdDup

            # Set the translation mode and buffering.
            self._mode = 't'
            if self._mode == 't':
                flags = os.O_TEXT
            else:
                flags = 0
            fdChildStdinWr = msvcrt.open_osfhandle(self._hChildStdinWr, flags)
            fdChildStdoutRd = msvcrt.open_osfhandle(self._hChildStdoutRd,
                                                    flags)
            fdChildStderrRd = msvcrt.open_osfhandle(self._hChildStderrRd,
                                                    flags)

            self.stdin = _FileWrapper(descriptor=fdChildStdinWr,
                                      handle=self._hChildStdinWr)
            logres.info("[%s] Process._start(): create child stdin: %r",
                        id(self), self.stdin)
            self.stdout = _FileWrapper(descriptor=fdChildStdoutRd,
                                       handle=self._hChildStdoutRd)
            logres.info("[%s] Process._start(): create child stdout: %r",
                        id(self), self.stdout)
            self.stderr = _FileWrapper(descriptor=fdChildStderrRd,
                                       handle=self._hChildStderrRd)
            logres.info("[%s] Process._start(): create child stderr: %r",
                        id(self), self.stderr)

            si.hStdInput = hChildStdinRd
            si.hStdOutput = hChildStdoutWr
            si.hStdError = hChildStderrWr
            #si.wShowWindow = show
            si.wShowWindow = 1
            si.dwFlags |= win32process.STARTF_USESTDHANDLES

            creation_flags = win32process.CREATE_NEW_CONSOLE
            (self.mProcess, self.mThread, self.mProcessId, self.mThreadId)\
               = _safeCreateProcess(
                  self.mAvatar,    # Avatar
                  None,            # App name
                  cmd,             # Command
                  None,            # Process security attribs
                  None,            # Primary thread security attribs
                  1,               # Handles are inherited
                  creation_flags,  # Creation Flags
                  self.mEnv,       # Environment
                  self.mCwd,       # Current Working Directory
                  si)              # STARTUPINFO

        finally:
            # Close child ends of pipes on the parent's side (the
            # parent's ends of the pipe are closed in the _FileWrappers.)
            win32file.CloseHandle(hChildStdinRd)
            win32file.CloseHandle(hChildStdoutWr)
            win32file.CloseHandle(hChildStderrWr)
Пример #22
0
                                                 ntsecuritycon.SE_BACKUP_NAME),
              win32con.SE_PRIVILEGE_ENABLED),
             (win32security.LookupPrivilegeValue(
                 '', ntsecuritycon.SE_RESTORE_NAME),
              win32con.SE_PRIVILEGE_ENABLED))
ph = win32api.GetCurrentProcess()
th = win32security.OpenProcessToken(
    ph, win32security.TOKEN_ALL_ACCESS | win32con.TOKEN_ADJUST_PRIVILEGES)
win32security.AdjustTokenPrivileges(th, 0, new_privs)
my_sid = win32security.GetTokenInformation(th, ntsecuritycon.TokenUser)[0]

hklm = win32api.RegOpenKey(win32con.HKEY_LOCAL_MACHINE, None, 0,
                           win32con.KEY_ALL_ACCESS)
skey = win32api.RegOpenKey(hklm, 'SYSTEM', 0, win32con.KEY_ALL_ACCESS)

sa = pywintypes.SECURITY_ATTRIBUTES()
sd = pywintypes.SECURITY_DESCRIPTOR()
sa.SECURITY_DESCRIPTOR = sd
acl = pywintypes.ACL()

pwr_sid = win32security.LookupAccountName('', 'Power Users')[0]
acl.AddAccessAllowedAce(
    win32con.ACL_REVISION,
    win32con.GENERIC_READ | win32con.ACCESS_SYSTEM_SECURITY, my_sid)
sd.SetSecurityDescriptorDacl(1, acl, 0)
sd.SetSecurityDescriptorOwner(pwr_sid, 0)
sa.bInheritHandle = 1
assert sa.SECURITY_DESCRIPTOR is sd

win32api.RegSaveKey(skey, fname, sa)
Пример #23
0
    def SvcDoRun(self):
        # Log a "started" message to the event log.
        import servicemanager
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))

        # We create our named pipe.
        pipeName = "\\\\.\\pipe\\PyPipeService"
        openMode = win32pipe.PIPE_ACCESS_DUPLEX | win32file.FILE_FLAG_OVERLAPPED
        pipeMode = win32pipe.PIPE_TYPE_MESSAGE

        # When running as a service, we must use special security for the pipe
        sa = pywintypes.SECURITY_ATTRIBUTES()
        # Say we do have a DACL, and it is empty
        # (ie, allow full access!)
        sa.SetSecurityDescriptorDacl(1, None, 0)

        pipeHandle = win32pipe.CreateNamedPipe(
            pipeName,
            openMode,
            pipeMode,
            win32pipe.PIPE_UNLIMITED_INSTANCES,
            0,
            0,
            6000,  # default buffers, and 6 second timeout.
            sa)

        # Loop accepting and processing connections
        while 1:
            try:
                hr = win32pipe.ConnectNamedPipe(pipeHandle, self.overlapped)
            except error, details:
                print "Error connecting pipe!", details
                pipeHandle.Close()
                break

            if hr == winerror.ERROR_PIPE_CONNECTED:
                # Client is fast, and already connected - signal event
                win32event.SetEvent(self.overlapped.hEvent)
            # Wait for either a connection, or a service stop request.
            timeout = win32event.INFINITE
            waitHandles = self.hWaitStop, self.overlapped.hEvent
            rc = win32event.WaitForMultipleObjects(waitHandles, 0, timeout)
            if rc == win32event.WAIT_OBJECT_0:
                # Stop event
                break
            else:
                # Pipe event - read the data, and write it back.
                # But first, increment our Performance Monitor data
                self.counterConnections.Increment()
                # (We only handle a max of 255 characters for this sample)
                try:
                    hr, data = win32file.ReadFile(pipeHandle, 256)
                    win32file.WriteFile(pipeHandle, "You sent me:" + data)
                    # And disconnect from the client.
                    win32pipe.DisconnectNamedPipe(pipeHandle)
                    # Update our performance monitor "bytes read" counter
                    self.counterBytes.Increment(len(data))

                    # Log a message to the event log indicating what we did.
                    message = "Processed %d bytes for client connection" % len(
                        data)
                    servicemanager.LogInfoMsg(message)
                except win32file.error:
                    # Client disconnected without sending data
                    # or before reading the response.
                    # Thats OK - just get the next connection
                    continue
Пример #24
0
def main(source, destination, job_name, version):
    extensions = set(('.pdb', '.dll', '.exe', '.ocx'))
    files_copied = 0

    starttime = datetime.datetime.now()
    log("Start " + starttime.isoformat())
    destdir = tempfile.mkdtemp()
    log("destination %s" % destdir)

    for root, dirs, files in os.walk(source):
        #print dirs
        for filename in (f for f in files if f[-4:] in extensions):
            pdb_dir = os.path.join(destdir, os.path.relpath(root, source))
            try:
                os.makedirs(pdb_dir)
            except WindowsError as err:
                if err.winerror != 183:
                    raise
            # print os.path.join(pdb_dir, filename)
            win32file.CreateHardLink(os.path.join(pdb_dir, filename),
                                     os.path.join(root, filename))
            files_copied += 1
            #except pywintypes.error as err:
            # if err.winerror != 183: #pywintypes.error (183, 'CreateHardLink', 'Cannot create a file when that file already exists.')
        for exclude in ('.git', '.svn', 'CVS', '.hg', '3rdParty', 'Python27',
                        'Python26'):
            if exclude in dirs:
                dirs.remove(exclude)

    log("%d files copied" % files_copied)

    startup = win32process.STARTUPINFO()
    startup.dwFlags += win32process.STARTF_USESTDHANDLES
    startup.hStdInput = win32file.INVALID_HANDLE_VALUE
    security_attributes = pywintypes.SECURITY_ATTRIBUTES()
    security_attributes.bInheritHandle = 1
    log_path = os.path.join(destdir, "log")
    startup.hStdOutput = startup.hStdError = win32file.CreateFile(
        log_path, win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ,
        security_attributes, win32file.CREATE_ALWAYS, 0, None)
    win32file.WriteFile(startup.hStdOutput, 'log started\n')

    dtw_locations = (
        os.path.join(os.environ.get('ProgramFiles', r'C:\Program Files (x86)'),
                     'Debugging Tools for Windows (x86)'),
        os.path.join(os.environ.get('ProgramFiles', r'C:\Program Files'),
                     'Debugging Tools for Windows (x64)'),
        os.path.join(
            os.environ.get('ProgramFiles(x86)', r'C:\Program Files (x86)'),
            'Debugging Tools for Windows (x86)'),
        os.path.join(os.environ.get('ProgramW6432', r'C:\Program Files'),
                     'Debugging Tools for Windows (x64)'),
    )
    for dtw_location in dtw_locations:
        symstore = os.path.join(dtw_location, 'symstore.exe')
        if os.path.isfile(symstore):
            break
    else:
        raise Exception("Couldn't find symstore.exe in " +
                        ' '.join(dtw_locations) +
                        ". Is Debugging Tools for Windows installed?")

    (hProcess, hThread, processId, threadId) = win32process.CreateProcess(
        symstore,
        "symstore.exe add /r /f \"%s\" /s \"%s\" /t \"%s\" /v \"%s\"" %
        (destdir, destination, job_name, version), None, None, True,
        win32process.CREATE_BREAKAWAY_FROM_JOB, None, None, startup)
    win32api.CloseHandle(hThread)

    # Don't need to wait here, but it doesn't take long, and we can remove the temp dir
    import win32event
    win32event.WaitForSingleObject(hProcess, win32event.INFINITE)
    exit_code = win32process.GetExitCodeProcess(hProcess)
    log("symstore exited with code " + str(exit_code))
    win32api.CloseHandle(startup.hStdOutput)
    with file(log_path, "r") as log_file:
        for line in log_file:
            log("symstore: " + line.rstrip('\r\n'))
    import shutil
    shutil.rmtree(destdir)

    win32api.CloseHandle(hProcess)

    # print "\n".join(open(os.path.join(destdir, 'log'), 'r'))

    log("finish: %s" % datetime.datetime.now().isoformat())
    log("elapsed time: %d seconds" %
        (datetime.datetime.now() - starttime).seconds)
    return exit_code