通过 openSSH 在远程机器上执行 Powershell 命令

Powershell commands on remote machine via openSSH

我正在尝试通过 openSSH 和 运行 windows 框上的一些 powershell 命令从 linux 机器连接到 windows 机器。由于某些限制,我无法在 linux 盒子上安装 powershell。

从 linux 手动启动 openSSH,然后 运行ning 命令工作正常。

我正在尝试在 Java 中做同样的事情,但问题是我没有看到 powershell 命令的输出 运行。

下面是重现相同内容的代码:

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.

交互模式不适用于脚本和代码,因此不推荐使用。最好使用一些现有的 ssh 框架,如 jsch 来连接,这些框架作为开源的 maven 依赖项可用。