【问题标题】:Powershell commands on remote machine via openSSH通过 openSSH 在远程机器上执行 Powershell 命令
【发布时间】:2021-08-08 23:45:09
【问题描述】:

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

从 linux 手动启动 openSSH,然后运行命令运行良好。

我正在尝试在 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.

【问题讨论】:

  • “一些限制”?
  • 你在 main 的 static 上缺少 c
  • 我没有看到任何限制。这是流重定向的问题。我觉得。

标签: java powershell openssh


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2013-06-06
    • 2012-07-27
    • 1970-01-01
    • 2013-11-22
    • 1970-01-01
    • 2021-05-10
    • 2012-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多