一、创建SSH连接linux服务器操作命令工具类
package test.common;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.concurrent.TimeUnit;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
/**
* SSH连接linux服务器操作命令工具类
*/
public class SSHUtil {
private Channel channel;
private Session session = null;
public SSHUtil(final String ipAddress, final String username, final String password) throws Exception {
JSch jsch = new JSch();
this.session = jsch.getSession(username, ipAddress, 22);
this.session.setPassword(password);
this.session.setConfig("StrictHostKeyChecking", "no");
this.session.setTimeout(60000);
this.session.connect();
this.channel = this.session.openChannel("shell");
this.channel.connect(30000);
}
/**
* 执行操作命令
* @param cmd 命令
* @return
* @throws Exception
*/
public String runShell(String cmd) throws Exception {
String temp = null;
InputStream instream = null;
OutputStream outstream = null;
try {
instream = this.channel.getInputStream();
outstream = this.channel.getOutputStream();
outstream.write(cmd.getBytes());
outstream.flush();
TimeUnit.SECONDS.sleep(2);
if (instream.available() > 0) {
byte[] data = new byte[instream.available()];
int nLen = instream.read(data);
if (nLen < 0) {
throw new Exception("network error.");
}
temp = new String(data, 0, nLen, "UTF-8");
}
} finally {
outstream.close();
instream.close();
}
return temp;
}
/**
* 执行相关的命令可返回执行结果
* @param command 命令
* @return
* @throws Exception
*/
public String execCmd(String command) throws Exception{
BufferedReader reader = null;
Channel channel = null;
StringBuffer sb=new StringBuffer("");
channel = session.openChannel("exec");
((ChannelExec) channel).setCommand(command);
channel.setInputStream(null);
((ChannelExec) channel).setErrStream(System.err);
channel.connect();
InputStream in = channel.getInputStream();
reader = new BufferedReader(new InputStreamReader(in,
Charset.forName("utf-8")));
String buf = null;
while ((buf = reader.readLine()) != null) {
sb.append(buf);
}
reader.close();
return sb.toString();
}
/**
* 关闭SSH连接
*/
public void close() throws Exception{
this.channel.disconnect();
this.session.disconnect();
}
}
二、创建操作Tomcat重启工具类
/**
*
*/
package test.common;
import java.io.IOException;
import org.apache.log4j.Logger;
/**
* tomcat重启操作类
*/
public class TomcatUtil {
private static Logger logger = Logger.getLogger(TomcatUtil.class);
private String tomcatDir;
private int retryTime;
private String waitingTime;
public TomcatUtil(String tomcatDir, int retryTime, String waitingTime) {
this.tomcatDir = tomcatDir;
this.retryTime = retryTime;
this.waitingTime = waitingTime;
}
public static void main(String[] args) {
SSHUtil sshUtil =null;
TomcatUtil tomcatUtil =null;
try {
sshUtil = new SSHUtil("127.0.0.1", "root", "mima");
tomcatUtil =new TomcatUtil("/usr/local/tomcat/",10, "10000");
tomcatUtil.restartTomcat(sshUtil);
sshUtil.close();
sshUtil =null;
} catch (Exception e) {
e.printStackTrace();
if(sshUtil != null){
try {
sshUtil.close();
} catch (Exception e1) {
e1.printStackTrace();
}
sshUtil =null;
}
}
}
/**
* 重启Tomcat
* @param runtime
* @return
* @throws IOException
*/
public boolean restartTomcat(SSHUtil sshUtil) throws Exception{
logger.info("开始执行重启Tomcat...");
for (int i = 0; i < retryTime; i++) {
logger.info("执行关闭Tomcat第"+(i+1)+"次...");
if(isExistTomcatProcess(sshUtil)) {
try {
logger.info("kill命令强制结束进程关闭Tomcat...");
killTomcatBySoft(sshUtil);
logger.info("kill命令关闭Tomcat后等待"+waitingTime+"毫秒。。。");
Thread.sleep(Integer.valueOf(waitingTime));
} catch (InterruptedException e) {
e.printStackTrace();
logger.info("执行关闭Tomcat第"+(i+1)+"次...异常:",e);
}
}else {
logger.info("未发现需要执行关闭Tomcat第"+(i+1)+"次...");
break;
}
}
logger.info("执行关闭Tomcat完成!");
for (int i = 0; i < retryTime; i++) {
logger.info("执行启动Tomcat第"+(i+1)+"次...");
if(!isExistTomcatProcess(sshUtil)) {
startupTomcat(sshUtil);
try {
logger.info("启动Tomcat后等待"+waitingTime+"毫秒。。。");
Thread.sleep(Integer.valueOf(waitingTime));
} catch (InterruptedException e) {
e.printStackTrace();
logger.info("执行启动Tomcat第"+(i+1)+"次...异常:",e);
}
}else {
logger.info("执行启动Tomcat第"+(i+1)+"次...");
break;
}
}
if(isExistTomcatProcess(sshUtil)) {
logger.info("重启tomcat成功!");
return true;
}else {
logger.info("重启tomcat失败!");
return false;
}
}
/**
* 判断是否含有tomcat进程
* @param runtime
* @return
* @throws IOException
*/
public boolean isExistTomcatProcess(SSHUtil sshUtil) throws Exception {
String command = "ps -ef | grep "+this.tomcatDir .split("/")[this.tomcatDir .split("/").length-1]+"/ | grep -v grep | awk '{print $2}';";
return isExistProcess(sshUtil, command);
}
/**
* 判断当前进程中是否含有program
* @param runtime
* @param program
* @return
* @throws IOException
*/
public boolean isExistProcess(SSHUtil sshUtil, String command) throws Exception {
boolean isExistTomcatProcess = false;
String res = sshUtil.execCmd(command);
if(res.length() > 0) {
isExistTomcatProcess = true;
}
logger.info("判断是否含有tomcat进程:"+isExistTomcatProcess);
return isExistTomcatProcess;
}
/**
* 启动Tomcat
* @param runtime
* @throws IOException
*/
public void startupTomcat(SSHUtil sshUtil) throws Exception {
logger.info("执行启动Tomcat脚本程序:"+this.tomcatDir + "bin/startup.sh");
sshUtil.runShell(tomcatDir + "bin/startup.sh\n");
}
/**
* 强制kill结束Tomcat进程
* @param runtime
* @throws IOException
*/
public void killTomcatBySoft(SSHUtil sshUtil) throws Exception {
String command = "ps -ef | grep "+this.tomcatDir .split("/")[this.tomcatDir .split("/").length-1]+"/ | grep -v grep | awk '{print $2}';";
String res = sshUtil.execCmd(command);
if(res.length() > 0) {
sshUtil.execCmd("kill -9 "+res);
}
logger.info("执行kill 命令,关闭Tomcat");
}
public String getTomcatDir() {
return tomcatDir;
}
public void setTomcatDir(String tomcatDir) {
this.tomcatDir = tomcatDir;
}
public int getRetryTime() {
return retryTime;
}
public void setRetryTime(int retryTime) {
this.retryTime = retryTime;
}
public String getWaitingTime() {
return waitingTime;
}
public void setWaitingTime(String waitingTime) {
this.waitingTime = waitingTime;
}
}