I want to know how to programmatically execute commands (like “dir C:\” or “shutdown -r”, etc.) in Windows’ Command Prompt (CMD) and retrieve the resulted output, without displaying the black CMD window of course.
I suspect ->this link<- contains the list of required APIs, but I’m not sure which ones to pick, so need your assistance.
Basically this is what I need it for: I want to write simple client-server application (WinSock) where user can sit on the client end and execute commands in (and read replies from) the command prompt of server. Yes – just like Telnet works, but without Telnet, just Win32 API.
Suppose user wants to execute “dir” command on server. He types “dir” on client application, which sends request to the server application, where the command will be executed (as if it was physically typed in command prompt of server) and the output text will be sent back to the client application.
Although this answer is not a good one for portable software, it works exactly the way you need it if you are sure everything is ok:
This function executes
commandin shell (CMD in windows) if available.By “if everything is ok” I mean you have a shell in your OS and it is available to you. Generally, this should be true for windows.
If you call it with
NULL, it will give non-zero if shell is available. If you give an actual command, it either returns-1indicating an error (for example couldn’t spawn a process), or return status of the command which should be OS dependent. Perhaps what you would be most concerned with is “if the command failed” and you should be good by checking the return value against 0 (0 being good).Note that to get the output of the command, and you need to save the output somewhere. For example execute the
dircommand like this:and then retrieve its output from
temp.txt.