【问题标题】:Java program to run shell commands from a windows machine从 Windows 机器运行 shell 命令的 Java 程序
【发布时间】:2014-09-19 08:31:47
【问题描述】:

我正在尝试运行 Java 程序以在远程 (Linux) 机器上执行命令。我可以让 putty.exe 运行,然后使用 SSH 密钥连接到机器。但我无法运行“bash”“ps-ef”或“ls -la”等实际命令。当前使用 Java runtime.exec,不确定使用 java.lang.ProcessBuilder 是否有帮助?我究竟做错了什么 ?任何帮助/指导将不胜感激..提前致谢

package hello;

import java.io.*;
public class RuntimeExample {




     public static void main(String args[]) throws IOException {



    try{     


    Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec(new String[]{"C:\\Users\\yky90455\\Desktop\\putty.exe","abc@login.testserver.helloworld.co.uk","bash", "ps -ef"});


    InputStream is = process.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line;

    System.out.printf("Output of running the command is:");

    while ((line = br.readLine()) != null) {
        System.out.println(line);

      }                                                             

    } catch (Exception e) {
        e.printStackTrace();
    }
}   

}

【问题讨论】:

  • 为什么不使用 SSH 库,而不是使用 putty?
  • Java 的全部意义在于抽象远离操作系统。在诉诸本机命令之前,请始终搜索独立于平台的替代方案。在您的示例中,只需使用 Java 的 SSH 实现 - 例如 sshj
  • 感谢您的快速回复。我会检查 sshj 和 Jsch。
  • 请求下一个问题,可能是另一个线程。什么是最好的 SSH 库,可以帮助使用 SSH 密钥连接到远程 linux 机器并执行命令

标签: java shell runtime.exec


【解决方案1】:

尝试使用 Jsch From here 将 shell 脚本从 Java 执行到某个远程 Linux 机器。我已经研究过了,这真的很有趣。虽然你可能会发现理解这一点的文档很少,但你可以轻松克服。

【讨论】:

  • 感谢您的快速回复。我会检查 sshj 和 Jsch。
  • @joule_wonder:欢迎您。但是如果您选择 Jsch,请务必标记此答案 :)
【解决方案2】:

还可以考虑一下 ExpectJ,它是 TCL Expect 的包装器。自 2010 年中期以来,该项目似乎没有任何积极的开发,但我过去曾将其用于 SSH。

http://expectj.sourceforge.net/apidocs/expectj/SshSpawn.html

【讨论】:

    【解决方案3】:

    感谢您的所有回答。我试过Ganymed SSH-2 库。它适用于远程机器上的基本命令。如果遇到 SSH-2 的任何限制,我将不得不探索其他 API。

    【讨论】:

      【解决方案4】:
      public class triggerPutty {
          public static void main(String[] a) {
              try {
                  String command = "putty.exe user@abc.text.com -pw password -m C:\\containing_comman.txt";
                  Runtime r = Runtime.getRuntime();
                  Process p = null;
                  p = r.exec(command);
                  p.waitFor();
                  p.destroy();
              } catch (Exception e) {
                  e.printStackTrace();
              }    
          }
      }
      

      -m 有助于从该文件运行您的命令。
      您可以在该文件中保留 N 条命令。## Heading ##

      猜你喜欢
      • 1970-01-01
      • 2011-01-28
      • 1970-01-01
      • 1970-01-01
      • 2015-06-22
      • 1970-01-01
      • 2013-04-14
      相关资源
      最近更新 更多