def _stub(cmd_name, stdin_name, stdout_name, stderr_name): """INTERNAL: Stub process that will start up the child process.""" # Open the 4 pipes (command, stdin, stdout, stderr) cmd_pipe = CreateFile(cmd_name, GENERIC_READ|GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None) SetHandleInformation(cmd_pipe, HANDLE_FLAG_INHERIT, 1) stdin_pipe = CreateFile(stdin_name, GENERIC_READ, 0, None, OPEN_EXISTING, 0, None) SetHandleInformation(stdin_pipe, HANDLE_FLAG_INHERIT, 1) stdout_pipe = CreateFile(stdout_name, GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None) SetHandleInformation(stdout_pipe, HANDLE_FLAG_INHERIT, 1) stderr_pipe = CreateFile(stderr_name, GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None) SetHandleInformation(stderr_pipe, HANDLE_FLAG_INHERIT, 1) # Learn what we need to do.. header = _read_header(cmd_pipe) input = _parse_header(header) if 'command' not in input or 'args' not in input: ExitProcess(2) # http://msdn.microsoft.com/en-us/library/ms682499(VS.85).aspx startupinfo = STARTUPINFO() startupinfo.dwFlags |= STARTF_USESTDHANDLES | STARTF_USESHOWWINDOW startupinfo.hStdInput = stdin_pipe startupinfo.hStdOutput = stdout_pipe startupinfo.hStdError = stderr_pipe startupinfo.wShowWindow = SW_HIDE # Grant access so that our parent can open its grandchild. if 'parent_sid' in input: mysid = _get_current_sid() parent = ConvertStringSidToSid(input['parent_sid']) sattrs = _create_security_attributes(mysid, parent, access=PROCESS_ALL_ACCESS) else: sattrs = None try: res = CreateProcess(input['command'], input['args'], sattrs, None, True, CREATE_NEW_CONSOLE, os.environ, os.getcwd(), startupinfo) except WindowsError as e: message = _quote_header(str(e)) WriteFile(cmd_pipe, 'status=error\nmessage=%s\n\n' % message) ExitProcess(3) else: pid = res[2] # Pass back results and exit err, nbytes = WriteFile(cmd_pipe, 'status=ok\npid=%s\n\n' % pid) ExitProcess(0)
def write_zero_fill(file_handle, write_length): # Bytearray will be initialized with null bytes as part of constructor. # Bytearray는 null 바이트로 초기화 # Write_length는 쓸 바이트 수 fill_string = bytearray(write_buf_size) assert len(fill_string) == write_buf_size # Loop and perform writes of write_buf_size bytes or less. # Continue until write_length bytes have been written. # There is no need to explicitly move the file pointer while # writing. We are writing contiguously. # write_buf_size 바이트 이하의 쓰기를 반복 # write_length byte가 작성될 때까지 계속합니다. while write_length > 0: if write_length >= write_buf_size: write_string = fill_string write_length -= write_buf_size else: write_string = fill_string[:write_length] write_length = 0 # Write buffer to file. #logger.debug("Write %d bytes", len(write_string)) #파일에 버퍼작성 _, bytes_written = WriteFile(file_handle, write_string) assert bytes_written == len(write_string) FlushFileBuffers(file_handle)
def write(self, data): if self._closed: return False try: WriteFile(self._conin_pipe, data) return True except: return False
def write( self, _cmd ): dbg_print( 'write: writing out --> ' + _cmd ) if self.using_pty: os.write( self.ind, _cmd ) else: osfh = msvcrt.get_osfhandle( self.ind ) ( errCode, written ) = WriteFile( osfh, _cmd )
def send(self, input): if not self.stdin: return None try: x = msvcrt.get_osfhandle(self.stdin.fileno()) # @UndefinedVariable (errCode, written) = WriteFile(x, input) except: return None return written
def send(self, data): if not self.stdin: return None try: x = msvcrt.get_osfhandle(self.stdin.fileno()) (errCode, written) = WriteFile(x, data) except ValueError: return self._close('stdin') except (subprocess.pywintypes.error, Exception), why: if why[0] in (109, ESHUTDOWN): return self._close('stdin') print "Error: Shell no stdin"
def send(self, input): if not self.stdin: return None try: x = msvcrt.get_osfhandle(self.stdin.fileno()) (errCode, written) = WriteFile(x, input) except ValueError: return self._close('stdin') except (subprocess.pywintypes.error, Exception), why: if why.args[0] in (109, errno.ESHUTDOWN): return self._close('stdin') raise
def send(self, input): if not self.stdin: return None try: x = msvcrt.get_osfhandle(self.stdin.fileno()) (_, written) = WriteFile(x, input) except ValueError: return self._close('stdin') except (subprocess.pywintypes.error, Exception) as ex: if (ex[0] if six.PY2 else ex.errno) in (109, errno.ESHUTDOWN): return self._close('stdin') raise return written
def send(self, input): if not self.stdin: return None try: x = msvcrt.get_osfhandle(self.stdin.fileno()) (errCode, written) = WriteFile(x, input) except ValueError: self._log_debug("close stdin") return self._close("stdin") except (subprocess.pywintypes.error, Exception) as why: if why[0] in (109, errno.ESHUTDOWN): self._log_debug("close stdin") return self._close("stdin") raise return written
def send(self, input): if not self.stdin: return None try: x = msvcrt.get_osfhandle(self.stdin.fileno()) (errCode, written) = WriteFile(x, input) # self._stdin_logger.debug(input.rstrip()) except ValueError: return self._close("stdin") except (pywintypes.error, Exception) as why: if why.args[0] in (109, errno.ESHUTDOWN): return self._close("stdin") raise return written
def send(self, data): self._logger.debug('send: %d', len(data)) size = len(data) while size: err, lwrite = WriteFile(self.fd, data[-size:], None) if err: raise OSError(err) size -= lwrite if self.notify: self._logger.debug('send: notifying router') self.w_terminator.sendall(NUL + NUL) self.notify = not self.notify
def send(self, input): if not self.stdin: return None import pywintypes try: x = msvcrt.get_osfhandle(self.stdin.fileno()) (errCode, written) = WriteFile(x, input) except ValueError: return self._close('stdin') except (pywintypes.error, Exception) as why: if why.winerror in (109, errno.ESHUTDOWN): return self._close('stdin') raise return written
def send(self, input): if not self.stdin: return None try: x = msvcrt.get_osfhandle(self.stdin.fileno()) (_, written) = WriteFile(x, input) except ValueError: return self._close('stdin') except Exception as ex: if getattr(ex, "args", None) and ex.args[0] in (109, errno.ESHUTDOWN): return self._close('stdin') raise return written
def send(self, input): '''Send input to stdin Usage: instance.send( input ) input - input to be sent''' if not self.stdin: return None try: x = msvcrt.get_osfhandle(self.stdin.fileno()) (errCode, written) = WriteFile(x, input) except ValueError: return self._close('stdin') except (subprocess.pywintypes.error, Exception), why: if why[0] in (109, errno.ESHUTDOWN): return self._close('stdin') raise
def send(self, input): if not self.stdin: return None try: if not hasattr(self, 'InHandle'): self.InHandle = msvcrt.get_osfhandle(self.stdin.fileno()) errCode, written = WriteFile(self.InHandle, input) except ValueError: return self._close('stdin') except SystemExit: raise except (subprocess.pywintypes.error, Exception) as why: if why[0] in (109, errno.ESHUTDOWN): return self._close('stdin') raise return written
def send(self, input_): r"""Send *input_* to the subprocess's standard input.""" if not self.stdin: return None try: x = msvcrt.get_osfhandle(self.stdin.fileno()) (errCode, written) = WriteFile(x, bytearray(input_, self._encoding)) except ValueError: return self._close('stdin') # except (subprocess.pywintypes.error, Exception): except pywintypes.error: why = sys.exc_info()[1] if why.winerror in (109, errno.ESHUTDOWN): return self._close('stdin') raise return written
def _transact(self, query): try: h = CreateFile( self.pipe_name, GENERIC_READ|GENERIC_WRITE, 0, None, OPEN_EXISTING, 0, None ) packet = self._construct_query(query) WriteFile(h, packet) read = 0 err, out = ReadFile(h, DI_PIPE_BUF_SIZE) length = struct.unpack('i', out[:SIZEOF_INT])[0] while len(out[SIZEOF_INT:]) < length: out += ReadFile(h, DI_PIPE_BUF_SIZE)[1] data = json.loads(out[SIZEOF_INT:], encoding='utf-8') except pywintypes.error as e: print e else: return data
def _spawn(self, command, args=None): """Start the child process. If args is empty, command will be parsed according to the rules of the MS C runtime, and args will be set to the parsed args.""" if args: args = args[:] # copy args.insert(0, command) else: args = split_command_line(command) command = args[0] self.command = command self.args = args command = which(self.command) if command is None: raise ExceptionPexpect('Command not found: %s' % self.command) args = join_command_line(self.args) # Create the pipes sids = [_get_current_sid()] if self.username and self.password: sids.append(_lookup_sid(self.domain, self.username)) cmd_pipe, cmd_name = _create_named_pipe(self.pipe_template, sids) stdin_pipe, stdin_name = _create_named_pipe(self.pipe_template, sids) stdout_pipe, stdout_name = _create_named_pipe(self.pipe_template, sids) stderr_pipe, stderr_name = _create_named_pipe(self.pipe_template, sids) startupinfo = STARTUPINFO() startupinfo.dwFlags |= STARTF_USESHOWWINDOW startupinfo.wShowWindow = SW_HIDE python = os.path.join(sys.exec_prefix, 'python.exe') pycmd = 'import winpexpect; winpexpect._stub(r"%s", r"%s", r"%s", r"%s")' \ % (cmd_name, stdin_name, stdout_name, stderr_name) pyargs = join_command_line([python, '-c', pycmd]) # Create a new token or run as the current process. if self.username and self.password: token = LogonUser(self.username, self.domain, self.password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT) res = CreateProcessAsUser(token, python, pyargs, None, None, False, CREATE_NEW_CONSOLE, self.env, self.cwd, startupinfo) else: token = None res = CreateProcess(python, pyargs, None, None, False, CREATE_NEW_CONSOLE, self.env, self.cwd, startupinfo) child_handle = res[0] res[1].Close() # don't need thread handle ConnectNamedPipe(cmd_pipe) ConnectNamedPipe(stdin_pipe) ConnectNamedPipe(stdout_pipe) ConnectNamedPipe(stderr_pipe) # Tell the stub what to do and wait for it to exit WriteFile(cmd_pipe, 'command=%s\n' % command) WriteFile(cmd_pipe, 'args=%s\n' % args) if token: parent_sid = ConvertSidToStringSid(_get_current_sid()) WriteFile(cmd_pipe, 'parent_sid=%s\n' % str(parent_sid)) WriteFile(cmd_pipe, '\n') header = _read_header(cmd_pipe) output = _parse_header(header) if output['status'] != 'ok': m = 'Child did not start up correctly. ' m += output.get('message', '') raise ExceptionPexpect(m) self.pid = int(output['pid']) self.child_handle = OpenProcess(PROCESS_ALL_ACCESS, False, self.pid) WaitForSingleObject(child_handle, INFINITE) # Start up the I/O threads self.child_fd = open_osfhandle(stdin_pipe.Detach(), 0) # for pexpect self.stdout_handle = stdout_pipe self.stdout_reader = Thread(target=self._child_reader, args=(self.stdout_handle,)) self.stdout_reader.start() self.stderr_handle = stderr_pipe self.stderr_reader = Thread(target=self._child_reader, args=(self.stderr_handle,)) self.stderr_reader.start() self.terminated = False self.closed = False
def _pipe_write(self, buf): log("pipe_write: %s", binascii.hexlify(buf)) WriteFile(self.pipe_handle, buf) FlushFileBuffers(self.pipe_handle) #SetFilePointer(self.pipe_handle, 0, FILE_BEGIN) return len(buf)
def osnmwrite(fd, data): # WriteFile(handle, buf, sizeof(*msg) + msg->len, &bytes_written, NULL) # http://docs.activestate.com/activepython/2.7/pywin32/win32file__WriteFile_meth.html # int, int = WriteFile(hFile, data , ol ) errCode, lwrite = WriteFile(fd, data, None) return lwrite