def _send_control_message(data: bytes): slot = win32file.CreateFile(_transport_control_slot(), win32file.GENERIC_WRITE, win32file.FILE_SHARE_READ, None, win32file.OPEN_EXISTING, 0, None) win32file.WriteFile(slot, data) win32file.CloseHandle(slot)
def write(self, text, close=False): "close - close pipe to emulate EOF" win32pipe.ConnectNamedPipe(self.pipe, None) text += self.lineterm win32file.WriteFile(self.pipe, text.encode(self.encoding)) if close: # http://comp.os.linux.questions.narkive.com/2AW9g5yn/sending-an-eof-to-a-named-pipe self.close() else: win32pipe.DisconnectNamedPipe(self.pipe)
def close(self): """Closes the channel to the client.""" try: # 2->TODO struct.pack|unpack in python < 2.7.7 does not allow unicode format string. win32file.WriteFile(self.__pipe_handle, compat.struct_pack_unicode("I", 0)) win32file.FlushFileBuffers(self.__pipe_handle) finally: win32pipe.DisconnectNamedPipe(self.__pipe_handle) self.__pipe_handle = None
def write(self, message): """ Writes string data to the connected pipe. """ try: data = str.encode(f"{message}") win32file.WriteFile(self.handle, data) return True except: return False
def _write(self, command): """ Platform independent button write function. """ if platform.system() == "Windows": try: win32file.WriteFile(self.pipe, command.encode()) except pywintypes.error: pass else: self.pipe.write(command)
def write(self, msg): try: if not self.__fifo: self.open(mode='write') print(f'Sending message {msg} to the client') win32file.WriteFile(self.__fifo, msg) print(f'Message sent successfully') except Exception as exp: print(exp) finally: self.close()
def write(self, s): try: win32file.WriteFile(self._hfile, s, self._write_ovrlpd) return win32file.GetOverlappedResult(self._hfile, self._write_ovrlpd, True) except: logging.debug("Exception writing to VirtIO", exc_info=True) # We do sleep here to avoid constant writes to spike the CPU time.sleep(1) return 0
def transmit(self, dataToTransmit): # convert to string dataToTransmit = ''.join([chr(b) for b in dataToTransmit]) # write over tuntap interface win32file.WriteFile(self.tuntap, dataToTransmit, self.overlappedTx) win32event.WaitForSingleObject(self.overlappedTx.hEvent, win32event.INFINITE) self.overlappedTx.Offset = self.overlappedTx.Offset + len( dataToTransmit)
def write(self, data: bytes): if self.__handler and self.__connected: try: (err, bytes_written) = win32file.WriteFile(self.__handler, data) if bytes_written > 0: return True except Exception: self.close() pass return False
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
def _serverThread(self, pipe_handle, event, wait_time): # just do one connection and terminate. hr = win32pipe.ConnectNamedPipe(pipe_handle) self.failUnless(hr in (0, winerror.ERROR_PIPE_CONNECTED), "Got error code 0x%x" % (hr, )) hr, got = win32file.ReadFile(pipe_handle, 100) self.failUnless(got == "foo\0bar") time.sleep(wait_time) win32file.WriteFile(pipe_handle, "bar\0foo") pipe_handle.Close() event.set()
def write(self, s): """Output the given string over the serial port.""" if not self.hComPort: raise portNotOpenError #print repr(s), if s: err, n = win32file.WriteFile(self.hComPort, s, self._overlappedWrite) if err: #will be ERROR_IO_PENDING: # Wait for the write to complete. win32event.WaitForSingleObject(self._overlappedWrite.hEvent, win32event.INFINITE)
def _write_to_pipe(self, data): """ Writes data to the pipe. :param data: data to write """ if sys.platform.startswith('win'): win32file.WriteFile(self._pipe, data) else: self._pipe.sendall(data)
def Transmit(self, transmitData): """ This will be called to detect available IR Blasters. """ if not self.file: return False writeOvlap = win32file.OVERLAPPED() writeOvlap.hEvent = win32event.CreateEvent(None, 0, 0, None) win32file.WriteFile(self.file, transmitData, writeOvlap) win32event.WaitForSingleObject(writeOvlap.hEvent, win32event.INFINITE) return True
def write_named_pipe(name, value): fileh = None try: fileh = win32file.CreateFile(r'\\.\pipe\{name}'.format(name=name), win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) win32file.WriteFile(fileh, value) except WinError: pass finally: if fileh is not None: win32api.CloseHandle(fileh)
def write(self, s): "write string to serial port" if not self.hComPort: raise portNotOpenError #print repr(s), overlapped = win32file.OVERLAPPED() overlapped.hEvent = win32event.CreateEvent(None, 1, 0, None) err, n = win32file.WriteFile(self.hComPort, s, overlapped) if err: #will be ERROR_IO_PENDING: # Wait for the write to complete. win32event.WaitForSingleObject(overlapped.hEvent, win32event.INFINITE)
def log(data): """ Output string or binary to file and/or server. """ if type(data) == str: data = data.encode(TARGET_ENCODING) LOG_LOCK.acquire() if FILE_LOG: FILE_LOG.write(data) if H_PIPE: win32file.WriteFile(H_PIPE, data) LOG_LOCK.release()
def _write_pipe(self, buf): try: # WINDOWS: win32file.WriteFile(self._pipe, bytes(buf)) # UNIX: #self._pipe.write(buf) except OSError as e: # SIGPIPE indicates the fifo was closed if e.errno == errno.SIGPIPE: return False return True
def uploadToGD(lvl): try: handle = win32file.CreateFile( '\\\\.\\pipe\\GDPipe', win32file.GENERIC_READ | win32file.GENERIC_WRITE, 0, None, win32file.OPEN_EXISTING, 0, None) for blks in chunks(lvl.blocks, 30): blocks = ';'.join([str(x) for x in blks]) + ';' win32file.WriteFile(handle, blocks.encode()) except Exception as e: print("theres an error lmao") raise
def run(self, security_attributes): """ Handles the creation of the pipe. Windows SACL and DACL data for creating the pipe. :type security_attributes: win32security.SECURITY_ATTRIBUTES instance :return: None :rtype: None """ import eg eg.PrintDebugNotice('Named Pipe: Creating pipe {0}'.format( self._pipe_id)) pipe = win32pipe.CreateNamedPipe( r'\\.\pipe\eventghost', PIPE_ACCESS_DUPLEX, PIPE_TYPE_MESSAGE | PIPE_WAIT | PIPE_READMODE_MESSAGE, PIPE_UNLIMITED_INSTANCES, 4096, 4096, 5, security_attributes) win32pipe.ConnectNamedPipe(pipe, None) data = win32file.ReadFile(pipe, 4096) self.is_waiting = False if not self._parent.running_pipes[-1].is_waiting == self: self._parent.running_pipes += [ Pipe(self._parent, self._parent.get_pipe_id(), security_attributes) ] eg.PrintDebugNotice('Pipe {0}: Data received'.format(self._pipe_id)) if data[0] == 0: event = threading.Event() res = [''] self._parent.process_command.add(self._pipe_id, data[1], res, event) while not event.isSet(): pass win32file.WriteFile(pipe, str(repr(res[0]))) win32pipe.DisconnectNamedPipe(pipe) win32file.CloseHandle(pipe) else: try: raise NamedPipeDataError('Pipe {0}: Unknown Error: {1}'.format( self._pipe_id, str(data))) except NamedPipeDataError: traceback.print_exc() self._parent.running_pipes.remove(self)
def _write(self, command): """ Platform independent button write function. """ if self.verbose: print("Controller {} is writing command {}".format(self.port, command)) if platform.system() == "Windows": try: win32file.WriteFile(self.pipe, command.encode()) except pywintypes.error: pass else: self.pipe.write(command)
def outputPacket(packet): ts_sec = int(time.time()) ts_usec = int((time.time() - ts_sec) * 1000000) header = bytearray() header.append((ts_sec >> 24) & 0xff) # timestamp seconds header.append((ts_sec >> 16) & 0xff) # timestamp seconds header.append((ts_sec >> 8) & 0xff) # timestamp seconds header.append((ts_sec >> 0) & 0xff) # timestamp seconds header.append((ts_usec >> 24) & 0xff) # timestamp microseconds header.append((ts_usec >> 16) & 0xff) # timestamp microseconds header.append((ts_usec >> 8) & 0xff) # timestamp microseconds header.append((ts_usec >> 0) & 0xff) # timestamp microseconds header.extend([0, 0, len(packet) >> 8, len(packet) & 0xff]) # nr of octets of packet saved header.extend([0, 0, len(packet) >> 8, len(packet) & 0xff]) # actual length of packet if outputIsFile: output.write(header) output.write(packet) else: win32file.WriteFile(output, header) win32file.WriteFile(output, packet)
def func_write(): PIPE_NAME = r'\\.\pipe\test_pipe' PIPE_BUFFER_SIZE = 1 named_pipe = win32pipe.CreateNamedPipe(PIPE_NAME, win32pipe.PIPE_ACCESS_DUPLEX, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT | win32pipe.PIPE_READMODE_MESSAGE, win32pipe.PIPE_UNLIMITED_INSTANCES, PIPE_BUFFER_SIZE, PIPE_BUFFER_SIZE, 500, None) win32pipe.ConnectNamedPipe(named_pipe, None) while True: win32file.WriteFile('1'.encode())
def pipe_server(): logging.info('pipe server start ...') count = 0 pipe = win32pipe.CreateNamedPipe( r'\\.\pipe\testpipe', # pipe name \\.\pipe\<pipename> win32pipe.PIPE_ACCESS_DUPLEX, # open mode win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_READMODE_MESSAGE | win32pipe.PIPE_WAIT, # pipe mode 1, # max Instance for the pipe 65536, # Out buffer size eg: 16bit 65536, # In buffer size eg: 16bit 0, # default time out None) # Security attribute try: logging.info('Waiting response from client') win32pipe.ConnectNamedPipe(pipe, None) logging.info('Received respond from client ') # while count < 10: # # convert to bytes # some_data = str(count).encode() # logging.info(f'Generate data {some_data}') # p = subprocess.Popen([sys.executable, 'print_input.py'], # stdin=subprocess.PIPE, # stdout=subprocess.PIPE, # stderr=subprocess.PIPE) # out, err = p.communicate(input=some_data) # logging.info(f'writing message {out}') # win32file.WriteFile( # return error code # pipe, # filehandle # out) # string # time.sleep(1) # count += 1 # logging.info('finihsed') loop = True while loop: hr, msg = win32file.ReadFile(pipe, 64 * 1024) if not hr: logging.info(f'Received input message: {msg}') p = subprocess.Popen([sys.executable, 'print_input.py'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = p.communicate(input=msg) logging.info(f'writing message {out}') win32file.WriteFile(pipe, out) logging.info(f'Done sent message') time.sleep(1) msg = msg.decode() if 'stop' in msg: logging.info(f'Stopping') loop = False finally: win32file.CloseHandle(pipe)
def Write(self, message): ''' Write a message to the open pipe. This generally shouldn't block (plenty of room in pipe), but will explicitly not-block if Set_Nonblocking has been called. ''' # Similar to above, ignore this error, rely on exceptions. # Data will be utf8 encoded. # Don't worry about non-blocking full-pipe exceptions for now; # assume there is always room. error, bytes_written = win32file.WriteFile(self.pipe_file, str(message).encode()) return
def write(self, buffer): """ Write to the stdin pipe. :param buffer: encoded bytes buffer. Normally utf-8 :return: # bytes written """ error, written = win32file.WriteFile(self.hChildStdinWr, buffer) if error: logger.error('write() Error: -> %s', win32api.GetLastError()) # win32file.FlushFileBuffers(self.hChildStdinWr) return written
def send_command(self, command, pin, val, arg4=None): """Pack and send a command to the client""" data = command + chr(pin) + chr(val) + (arg4 or "") print("Send: %s" % repr(data)) if self.sock: self.sock.send(data) elif self.pipe and self.pipe_status == "connected": try: win32file.WriteFile(self.pipe, data, None) except: print("Write failed, reconnecting") self.pipe_connect()
def __init__(self): self.pipe_h = win32pipe.CreateNamedPipe( WIRESHARK_PIPE, win32pipe.PIPE_ACCESS_OUTBOUND, win32pipe.PIPE_TYPE_MESSAGE | win32pipe.PIPE_WAIT, 1, 65536, 65536, 300, None) logging.info( "Waiting for wireshark to connect to pipe '%(WIRESHARK_PIPE)s'" % globals()) win32pipe.ConnectNamedPipe(self.pipe_h, None) win32file.WriteFile(self.pipe_h, INITIAL_PCAP_HEADER)
def testMoreFiles(self): # Create a file in the %TEMP% directory. testName = os.path.join(win32api.GetTempPath(), "win32filetest.dat") desiredAccess = win32file.GENERIC_READ | win32file.GENERIC_WRITE # Set a flag to delete the file automatically when it is closed. fileFlags = win32file.FILE_FLAG_DELETE_ON_CLOSE h = win32file.CreateFile(testName, desiredAccess, win32file.FILE_SHARE_READ, None, win32file.CREATE_ALWAYS, fileFlags, 0) # Write a known number of bytes to the file. data = str2bytes("z") * 1025 win32file.WriteFile(h, data) self.failUnless( win32file.GetFileSize(h) == len(data), "WARNING: Written file does not have the same size as the length of the data in it!" ) # Ensure we can read the data back. win32file.SetFilePointer(h, 0, win32file.FILE_BEGIN) hr, read_data = win32file.ReadFile(h, len(data) + 10) # + 10 to get anything extra self.failUnless(hr == 0, "Readfile returned %d" % hr) self.failUnless(read_data == data, "Read data is not what we wrote!") # Now truncate the file at 1/2 its existing size. newSize = len(data) // 2 win32file.SetFilePointer(h, newSize, win32file.FILE_BEGIN) win32file.SetEndOfFile(h) self.failUnlessEqual(win32file.GetFileSize(h), newSize) # GetFileAttributesEx/GetFileAttributesExW tests. self.failUnlessEqual(win32file.GetFileAttributesEx(testName), win32file.GetFileAttributesExW(testName)) attr, ct, at, wt, size = win32file.GetFileAttributesEx(testName) self.failUnless( size == newSize, "Expected GetFileAttributesEx to return the same size as GetFileSize()" ) self.failUnless( attr == win32file.GetFileAttributes(testName), "Expected GetFileAttributesEx to return the same attributes as GetFileAttributes" ) h = None # Close the file by removing the last reference to the handle! self.failUnless(not os.path.isfile(testName), "After closing the file, it still exists!")
def SendData(self, data): try: if not self.hasClient: win32pipe.ConnectNamedPipe(self.pipe, None) self.hasClient = True win32file.WriteFile(self.pipe, data) win32file.FlushFileBuffers(self.pipe) except Exception: if self.hasClient: win32pipe.DisconnectNamedPipe(self.pipe) self.hasClient = False return