I am trying to run a shell script on a remote server using a JAVA API. The remote server has authentication , so i have to pass my username and password to login to it. I do not have the rights on these machines (neither source nor destination) to install 'sshpass' , in case you were going to give that solution.
What is the best way to do this?
答案 0 :(得分:4)
JSch is an excellent library for supporting remote connections over ssh, including the execution of remote commands (or shell scripts).
There are numerous examples of how to use JSch at JSch Examples, but pay particular attention to Exec.
At its base, what one does is:
Session
Channel
within the Session
While typing, the OP also posted an additional question and an example. The example from http://www.codesandscripts.com/2014/10/java-program-to-execute-shell-scripts-on-remote-server.html seems fine as well.
As to the pushing the script to the server, start by using either scp
or sftp
(the latter we've found to be more reliable) to move the file to the remote machine, be sure to send an exec
of chmod u+x
, and then invoke the script.
答案 1 :(得分:0)
这是一个JSch示例,可通过SSH登录(密码)远程服务器并运行Shell脚本。
package com.mkyong.io.howto;
import com.jcraft.jsch.*;
import java.io.IOException;
import java.io.InputStream;
public class RunRemoteScript {
private static final String REMOTE_HOST = "1.1.1.1";
private static final String USERNAME = "";
private static final String PASSWORD = "";
private static final int REMOTE_PORT = 22;
private static final int SESSION_TIMEOUT = 10000;
private static final int CHANNEL_TIMEOUT = 5000;
public static void main(String[] args) {
String remoteShellScript = "/root/hello.sh";
Session jschSession = null;
try {
JSch jsch = new JSch();
jsch.setKnownHosts("/home/mkyong/.ssh/known_hosts");
jschSession = jsch.getSession(USERNAME, REMOTE_HOST, REMOTE_PORT);
// not recommend, uses jsch.setKnownHosts
//jschSession.setConfig("StrictHostKeyChecking", "no");
// authenticate using password
jschSession.setPassword(PASSWORD);
// 10 seconds timeout session
jschSession.connect(SESSION_TIMEOUT);
ChannelExec channelExec = (ChannelExec) jschSession.openChannel("exec");
// run a shell script
channelExec.setCommand("sh " + remoteShellScript + " mkyong");
// display errors to System.err
channelExec.setErrStream(System.err);
InputStream in = channelExec.getInputStream();
// 5 seconds timeout channel
channelExec.connect(CHANNEL_TIMEOUT);
// read the result from remote server
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 (channelExec.isClosed()) {
if (in.available() > 0) continue;
System.out.println("exit-status: "
+ channelExec.getExitStatus());
break;
}
try {
Thread.sleep(1000);
} catch (Exception ee) {
}
}
channelExec.disconnect();
} catch (JSchException | IOException e) {
e.printStackTrace();
} finally {
if (jschSession != null) {
jschSession.disconnect();
}
}
}
}