访问 UNIX 服务器并从 Java 应用程序运行 shell 脚本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18401248/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 01:15:48  来源:igfitidea点击:

Access UNIX server and run a shell script from java application

javaunixssh

提问by Shibankar

I have got one requirement where i have to access a unix server and on that server i have to run a shell script with some parameter from my java application. Please suggest some solution with example.

我有一个要求,我必须访问一个 unix 服务器,并且在该服务器上我必须运行一个带有来自我的 java 应用程序的一些参数的 shell 脚本。请举例提出一些解决方案。

i have tried something but it is not working.

我试过一些东西,但它不起作用。

SshWrapper ssh = new SshWrapper();
 try {  
        ssh.connect("10.206.19.80", 22);  
        ssh.login("*****","*****");  

        ssh.setPrompt("c898vqz:~");  
        ssh.waitfor("#");
        System.out.println("PWD**********"+ssh.send("pwd"));  

        ssh.disconnect();
        System.out.println(ssh.getClass());
    } catch (java.io.IOException e) {  
        e.printStackTrace();  
    }

getting nullfrom ssh.send("pwd")

获得nullssh.send("pwd")

采纳答案by rook

You could use SSHcomponent JCraftfor remote connection and shell commands invocations:

您可以使用SSH组件JCraft进行远程连接和 shell 命令调用:

import com.jcraft.jsch.*

Exerp from my old code:

Exerp 来自我的旧代码:

JSch jsch = new JSch();

String command = "/tmp/myscript.sh";
Session session = jsch.getSession(user, host, 22);
session.connect();

Channel channel = session.openChannel("exec");
((ChannelExec)channel).setCommand(command);

channel.setInputStream(null);
((ChannelExec)channel).setErrStream(System.err);
InputStream in = channel.getInputStream();
channel.connect();

byte[] tmp = new byte[1024];
while (true) {
  while (in.available() > 0) {
      int i = in.read(tmp, 0, 1024);
      if (i < 0) {
          break;
      }
      System.out.print(new String(tmp, 0, i));
  }
  if (channel.isClosed()) {
      if (channel.getExitStatus() == 0) {
          System.out.println("Command executed successully.");
      }
      break;
  }
}
channel.disconnect();
session.disconnect();

You can also easily transfer files via session.openChannel("sftp").

您还可以通过session.openChannel("sftp").

ooph.. in javait is too wordy, than e.g. in rubyor python:)

哎呀.. injava太罗嗦了,比 inrubypython:)

回答by Rajat Kumar

JSch js = new JSch();
Session s = js.getSession("username", "ip", port);
s.setPassword("password");
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
s.setConfig(config);
s.connect();
System.out.println("connection ");
Channel c = s.openChannel("sftp");
ChannelSftp ce = (ChannelSftp) c;

ce.connect();
System.out.println("connection ");
ce.disconnect();
s.disconnect();