Goal: Running bat files remotely for test needs.
Requirements:
Situation:
I am running my code as java application on Windows 7. The application creates the process which runs cmd.exe to run bat from the local machine. The bat file contains a command for psexec to run another bat file remotely.
I have tried other ways without creating local bat file: tried to run psexec command, but failed to pass more than 1 argument.
Listing:
public static void main(String[] args) throws IOException,
InterruptedException
{
String[] command = { "cmd", };
Process p = Runtime.getRuntime().exec(command);
new Thread(new SyncPipe(p.getErrorStream(), System.err)).start();
new Thread(new SyncPipe(p.getInputStream(), System.out)).start();
PrintWriter stdin = new PrintWriter(p.getOutputStream());
stdin.println("cd C:\\Autotests\\Bat\\");
stdin.println(".\\localBat.bat");
// write any other commands you want here
stdin.close();
int returnCode = p.waitFor();
System.out.println("Return code = " + returnCode);
}
public static class SyncPipe implements Runnable
{
public SyncPipe(InputStream istrm, OutputStream ostrm)
{
istrm_ = istrm;
ostrm_ = ostrm;
}
public void run()
{
try
{
final byte[] buffer = new byte[1024];
for (int length = 0; (length = istrm_.read(buffer)) != -1;)
{
ostrm_.write(buffer, 0, length);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private final OutputStream ostrm_;
private final InputStream istrm_;
}
Contents of localBat.bat:
C:\\PSTools\\psexec.exe \\**.**.**.** -s -u domain\user -p password C:\somepath\remoteBat.bat
What's the problem?
If I run the localBat.bat manually from the command line I get all the output of the remoteBat.bat displayed in the console. But when I run my application, the remoteBat.bat runs, I get the exit code stroed but I don't get the entire output, only these lines:
PsExec v2.11 - Execute processes remotely
Copyright (C) 2001-2014 Mark Russinovich
Sysinternals - www.sysinternals.com
Connecting to **.**.**.**...
Starting PSEXESVC service on **.**.**.**...
Connecting with PsExec service on **.**.**.**...
Starting C:\somepath\remoteBat.bat on **.**.**.**...
C:\somepath\remoteBat.bat exited on **.**.**.** with error code 0.
Impact
I can't handle and analyze the situation when the exit code is different from 0.
Please, help me, I'm stuck here.