Reading & Writing other process’s STD handles in python

  Kiến thức lập trình

I am trying to use Pywin32 to get the STD handles of another process, then read and write to them.

My source code is:

import win32api
import win32con
import win32file

STD_INPUT_HANDLE = 10   
STD_OUTPUT_HANDLE = 11
STD_ERROR_HANDLE = 12

pid = 4908

process_handle = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid)

stdin_handle = win32api.GetStdHandle(STD_INPUT_HANDLE)
stdout_handle = win32api.GetStdHandle(STD_OUTPUT_HANDLE)
stderr_handle = win32api.GetStdHandle(STD_ERROR_HANDLE)

win32file.WriteFile(stdout_handle, b"Hello from Python!")

win32api.CloseHandle(process_handle)

It raises this error: pywintypes.error: (6, 'WriteFile', 'The handle is invalid.'). How can i work around this?

Note: I got the STD handle constants from here.

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT