Okay I am using plink and have the program launching well enough. I went back and worked thru the MSDN code and tried to apply it to what I have but I can't really tell what it is doing besides not working. I setup my plink connections as a seperate class called pconnect. I believe my main issues stem from the fact the MSDN code uses files to read from and write to and I am trying to read from and write to the cout/cin of my parent program. However, with the usage of handles to the sockets I thought this was possible. Here is some code:
main:
Code:
int main(int argc, char *argv[])
{
Pconnect connector;
string path, param;
char c;
path = "c:\\plink.exe";
param = "-ssh *username*@*server*";
int i = connector.ExecuteProcess(path, param, 0);
Sleep(5000);
connector.WriteToPipe("password\n");
cout << "Wrote it!\n";
connector.ReadFromPipe();
cout << "Execute process finished with: " << i << endl;
cin >> c; //dont close terminal window until characer is entered
}
Here is the pconnect header file. I am not sure if I should be defining the handles where I am but I didnt see why it should not work this way.
Code:
class Pconnect{
public:
int ExecuteProcess(std::string &FullPathToExe, std::string &Parameters, int SecondsToWait);
void WriteToPipe(std::string s);
char* ReadFromPipe();
private:
HANDLE hChildStdinRd, hChildStdinWr,
hChildStdoutRd, hChildStdoutWr,
hStdout;
};
Handle setup from what I gathered on the MSDN page: (this is happening inside ExecuteProcess)
Code:
//get handle of current stdout
hStdout = GetStdHandle(STD_OUTPUT_HANDLE);
//create a pipe for the child process's STDOUT
if(! CreatePipe(&hChildStdoutRd, &hChildStdoutWr, &as, 0))
std::cerr << "Stdout pipe creation failed.\n";
//Endure the read handle for STDOUT is not inherited.
SetHandleInformation( hChildStdoutRd, HANDLE_FLAG_INHERIT, 0);
//create pipe for childs STDIN
if(! CreatePipe(&hChildStdinRd, &hChildStdinWr, &as, 0))
std::cerr << "Stdin pipe creation failed.\n";
//Ensure write handle for STDIN is not inherited
SetHandleInformation( hChildStdinWr, HANDLE_FLAG_INHERIT, 0);
Write to pipe:
Code:
void Pconnect::WriteToPipe(string s)
{
DWORD dwWritten;
CHAR chBuf[BUFSIZE];
strcpy(chBuf, s.c_str());
// Read from a file and write its contents to a pipe.
if (! WriteFile(hChildStdinWr, chBuf, BUFSIZE,
&dwWritten, NULL))
std::cerr << "Write to pipe failed.\n";
// Close the pipe handle so the child process stops reading.
if (! CloseHandle(hChildStdinWr))
std::cerr << "Close pipe failed.\n";
}
Read from pipe:
Code:
char* Pconnect::ReadFromPipe()
{
DWORD dwRead, dwWritten;
CHAR chBuf[BUFSIZE];
// Close the write end of the pipe before reading from the
// read end of the pipe.
if (!CloseHandle(hChildStdoutWr))
std::cerr << "Closing handle failed.\n";
// Read output from the child process, and write to parent's STDOUT.
for (;;)
{
if( !
ReadFile( hChildStdoutRd, chBuf, BUFSIZE, &dwRead,
NULL) || dwRead == 0) break;
if (! WriteFile(hStdout, chBuf, dwRead, &dwWritten, NULL))
break;
}
return chBuf;
}