且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取cmd.exe的当前工作目录

更新时间:2023-01-27 15:36:21

未经验证,一种可能的方法:

Untested, a possible approach:

使用DllMain创建一个DLL,该DLL使用GetThreadStartInformation()来查找缓冲区的地址,然后使用GetCurrentDirectory进行填充。这应该是可以的,因为这两个函数都在kernel32中,它始终存在。您将需要有一些结构来返回成功/失败。

Create a DLL with a DllMain that uses GetThreadStartInformation() to find the address of the buffer, and then uses GetCurrentDirectory to populate it. This should be OK, because both of those functions are in kernel32, which is always present. You will need to have some structure there to return success/failure.


  1. 获取cmd.exe进程的句柄。

  2. 分配一些内存(VirtualAllocEx)

  3. 将DLL的路径放在内存中。 (WriteProcessMemory)

  4. 将您的DLL加载到cmd.exe地址空间中。 (CreateRemoteThread与LoadLibrary的入口点,参数是您之前分配的内存)。

  5. WaitForSingleObject后跟GetExitCodeThread(),在cmd.exe进程中提供您的DLL的HMODULE 。

  6. ReadProcessMemory获取当前目录。

  7. 从cmd.exe地址空间卸载你的DLL。 CreateRemote线程具有FreeLibrary的入口点,参数是HMODULE。

  8. WaitForSingleObject等待DLL卸载。

  1. Get a handle to the cmd.exe process.
  2. Allocate some memory there (VirtualAllocEx)
  3. Put the path to your DLL in the memory. (WriteProcessMemory)
  4. Load your dll into the cmd.exe address space. (CreateRemoteThread with an entry point of LoadLibrary, the argument is the memory you allocated earlier.)
  5. WaitForSingleObject followed by GetExitCodeThread(), gives you the HMODULE of your DLL in the cmd.exe process.
  6. ReadProcessMemory to get the current directory.
  7. Unload your dll from the cmd.exe address space. CreateRemote Thread with an entry point of FreeLibrary, the argument is the HMODULE.
  8. WaitForSingleObject to wait for the DLL to unload.

广泛草图:细节作为锻炼!风险:在cmd.exe地址空间中分配内存,更改其状态。必须注意DllMain中调用的函数。

Broad sketch: Details left as an excercise! Risks: Allocates memory in the cmd.exe address space, changes its state. Care must be taken with the functions called in DllMain.