How do I run multiple commands in SSH using Java runtime?
the command: ssh user@127.0.0.1 ‘export MYVAR=this/dir/is/cool; /run/my/script
/myscript; echo $MYVAR’
@Test
public void testSSHcmd() throws Exception
{
StringBuilder cmd = new StringBuilder();
cmd.append("ssh ");
cmd.append("user@127.0.0.1 ");
cmd.append("'export ");
cmd.append("MYVAR=this/dir/is/cool; ");
cmd.append("/run/my/script/myScript; ");
cmd.append("echo $MYVAR'");
Process p = Runtime.getRuntime().exec(cmd.toString());
}
The command by its self will work but when trying to execute from java run-time it does not. Any suggestions or advice?
Use the newer ProcessBuilder class instead of
Runtime.exec. You can construct one by specifying the program and its list of arguments as shown in my code below. You don’t need to use single-quotes around the command. You should also read the stdout and stderr streams andwaitForfor the process to finish.