1.需求(两台机器没有设置ssh免登陆)
shell 在另一台服务器上
代码在其他服务器上
2.要求:
在代码端的服务器 来调用另一台服务器上的shell
所需jar:commons-io-2.4.jar ganymed-ssh2-build210.jar
3.代码实现
conn = new Connection("192.77.210.202"); //远程shell所在服务器
conn.connect();
return conn.authenticateWithPassword("root", "1234");//服务器的用户名和密码
4.执行具体shell
Session session = conn.openSession();
// Execute a command on the remote machine.
session.execCommand(cmds);//执行对应shell
5.具体代码实现
public RemoteShellExecutorTask{
private Connection conn;
/** 远程机器IP */
private String ip;
/** 用户名 */
private String usr;
/** 密码 */
private String psword;
private String charset = Charset.defaultCharset().toString();
private static final int TIME_OUT = 1000 * 5 * 60;
/**
* 构造函数
* @param param 传入参数Bean 一些属性的getter setter 实现略
*/
public RemoteShellExecutorTask(ShellParamVO param) {
this.ip = param.getIp();
this.usr=param.getUsername();
this.psword=param.getPassword();
}
public RemoteShellExecutorTask(){}
/**
* 构造函数
* @param ip
* @param usr
* @param ps
*/
public RemoteShellExecutorTask(String ip, String usr, String ps) {
this.ip = ip;
this.usr = usr;
this.psword = ps;
}
/**
* 登录
*
* @return
* @throws IOException
*/
private boolean login() throws IOException {
conn = new Connection("132.77.210.202");
conn.connect();
return conn.authenticateWithPassword("root", "grid@1234");
}
/**
* 执行脚本
*
* @param cmds
* @return
* @throws Exception
*/
public int exec(String cmds) throws Exception {
InputStream stdOut = null;
InputStream stdErr = null;
String outStr = "";
String outErr = "";
int ret = -1;
try {
if (login()) {
// Open a new {@link Session} on this connection
Session session = conn.openSession();
// Execute a command on the remote machine.
session.execCommand(cmds);
stdOut = new StreamGobbler(session.getStdout());
outStr = processStream(stdOut, charset);
stdErr = new StreamGobbler(session.getStderr());
outErr = processStream(stdErr, charset);
session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);
System.out.println("outStr=" + outStr);
System.out.println("outErr=" + outErr);
ret = session.getExitStatus();
} else {
throw new Exception("登录远程机器失败" + ip); // 自定义异常类 实现略
}
} finally {
if (conn != null) {
conn.close();
}
IOUtils.closeQuietly(stdOut);
IOUtils.closeQuietly(stdErr);
}
return ret;
}
private String processStream(InputStream in, String charset) throws Exception {
byte[] buf = new byte[1024];
StringBuilder sb = new StringBuilder();
while (in.read(buf) != -1) {
sb.append(new String(buf, charset));
}
return sb.toString();
}
public static void main(String args[]) throws Exception {
RmtShellExecutor exe = new RmtShellExecutor();
// 执行myTest.sh 参数为java Know dummy
System.out.println(exe.exec("sh /script/shell/test1.sh"));
// exe.exec("uname -a && date && uptime && who");
}
}
public class ShellParamVO {
private String ip;
private String username;
private String password;
}
以上代码就可以实现 本地代码调用远程shell