介绍
这篇文章给大家分享的是有关java如何调用远程服务器的外壳脚本的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
最近接了个需求,要求远程调shell脚本,你没听错! ! !需求就一句话,咱是谁,咱是优秀的开发选手。考虑再三,有两种实现方式:
方案一:脚本所在服务器安装一个客户端,也就是自己写的一个小程序,本地通过端口调目标服务器的程序,然后程序调本机上的shell脚本!
优点:通过端口调用,用户不用暴露服务器的账号密码、安全性高
缺点:我们需要一直维护这个客户端程序,而且每接入一台服务器,都得安装该客户端,另外非常考验客户端程序的健壮性。
方案二:本地直接通过IP,服务器账号密码调远程服务器的外壳脚本
优点:代码易开发,扩展时只用扩展服务端代码即可
缺点:用户服务器的账号密码会暴露给服务端,密码安全问题
把每种方案的优缺点汇报给领导,领导说:按第二种来吧
来吧! !开干,废话不多说,直接上代码:
导入程序所需的软件包:
& lt; dependency> ,,& lt; groupId> org.jvnet.hudson ,,& lt; artifactId> ganymed-ssh3 ,,& lt; version> build210-hudson-1 & lt;/dependency>
程序涉及的演示:
import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import charset; , import org.apache.commons.io.IOUtils; , import ch.ethz.ssh3.ChannelCondition; import ch.ethz.ssh3.Connection; import ch.ethz.ssh3.Session; import ch.ethz.ssh3.StreamGobbler; , public class  RemoteShellExecutor { , ,,private Connection 康涅狄格州; ,,/* *,远程机器IP */,,private String 知识产权; ,,/* *,用户名,*/,,private String  osUsername; ,,/* *,密码,*/,,private String 密码; ,,private String  charset =, Charset.defaultCharset () .toString (); , ,,private final  String GET_SHELL_PID =,“ps -ef |, grep & # 39; % & # 39;, |, grep -v grep | awk & # 39; {print $ 2} & # 39;“; , ,,private final  String KILL_SHELL_PID =,“kill -15年,% s"; , ,,private static  final int TIME_OUT =, 1000, *, 5, *, 60; , ,,/* * ,,*,构造函数 ,,*,@param ip ,,*,@param usr ,,*,@param 密码 ,,*/,,public RemoteShellExecutor (String ip, String usr,, String 密码),{ ,,,,this.ip =, ip; ,,,,this.osUsername =, usr; ,,,,this.password =,密码; ,,} , , ,,/* * ,,*,登录 ,,* @return ,,*,@throws IOException ,,*/,,private boolean 登录(),throws IOException { ,,,,conn =, new 连接(ip); ,,,,conn.connect (); ,,,,return conn.authenticateWithPassword (osUsername,密码); ,,} , ,,/* * ,,*,执行脚本 ,,* ,,*,@param cmds ,,* @return ,,*,@throws 例外 ,,*/,,public ExecuteResultVO  exec (String cmds), throws Exception { ,,,,InputStream stdOut =,零,, ,,,,InputStream stdErr =,空; ,,,,ExecuteResultVO ExecuteResultVO =, new ExecuteResultVO (); ,,,,String outStr =,““ ,,,,String outErr =,““ ,,,,int ret =, 1; ,,,,try { ,,,,if (登录()),{ ,,,,,,//,Open a new {@link 会话},提醒却;能够连接 ,,,,,,Session Session =, conn.openSession (); ,,,,,,//,Execute a command 提醒,remote 机器。 ,,,,,,session.execCommand (cmds); , ,,,,,,stdOut =, new StreamGobbler (session.getStdout ()); ,,,,,,outStr =, processStream (stdOut,字符集); , ,,,,,,stdErr =, new StreamGobbler (session.getStderr ()); ,,,,,,outErr =, processStream (stdErr,字符集); , ,,,,,,session.waitForCondition (TIME_OUT ChannelCondition.EXIT_STATUS也); , null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null null nulljava如何调用远程服务器的外壳脚本