Skip to content
Advertisement

Powershell commands on remote machine via openSSH

I am trying to connect to a windows machine from a linux machine via openSSH and run some powershell commands on windows box. I cannot install powershell on linux box due to some restrictions.

Manually launching openSSH from linux and then running commands is working perfectly.

I am trying to do same thing in Java, but the problem is that I am not seeing output of powershell commands ran.

Below is the code to reproduce the same:

public class Example {
  public static class Writers exte ds Thread {
    Process process;
    Writers(Process p) {
      process =p;
    }
 
  public void run() {
    try {
      OutputStreamWriter writer= new OutputStreamWriter(process.getOutputStream);
      String command = "expect -c 'spawn ssh user@host ; expect "password" ; send "passcode\r"; interact' n";
      writer.write(command);
      writer.write("echo "hello123");
      writer.flush();
    } catch (Exception e) {}
    }
    
    public static void main(String[] args) throws Exception {
        ProcessBuilder builder = new ProcessBuilder("bash");
        builder.redirectErrorStream(true);
        Process process = builder.start();
        Example.Writers writers = new Example.Writers(process);
        writers.start();

        BufferedReader stdout = new BufferedReader( new InputStreamReader(process.getInputStream()));
        String s = null;
        while((s= stdout.readLine()) != null) {
           System.out.println(s);
        }
    }
}

OUTPUT:
I see only Windows powershell startup logo and nothing after that.

Tell me why this hello123 not getting printed.
Or, why the powershell output stream not getting redirected to output stream of linux machine ?

manually opening interactive ssh shell and running powershell commands run perfectly, but not via code.

Advertisement

Answer

interactive modes don’t work nice with scripts and codes and are not recommended. It’s better to use some existing ssh framework like jsch to connect, which are available as open source maven dependencies.

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement