- Tomcat重启脚本:
#! /bin/bash
tomcat_home=/usr/local/apache-tomcat-8.5.24
SHUTDOWN=$tomcat_home/bin/shutdown.sh
STARTTOMCAT=$tomcat_home/bin/startup.sh
echo "准备关闭$tomcat_home"
$SHUTDOWN &
#删除tomcat的临时目录
rm $tomcat_home/work/* -rf &
sleep 5 &
echo "准备启动$tomcat_home"
$STARTTOMCAT
#看启动日志
#tail -f $tomcat_home/logs/catalina.out
备注:将此脚本复制到代码中即可,不必存放在linux服务器文件下,避免路径出错
注意:脚本中每个方法后的&符号必须加上,如果不加则只执行第一个方法,后边的方法不继续执行
2. JAVA代码
private void restartTomcat() throws IOException{
//当前目录文件夹
File directory = new File("");
String binPath = directory.getAbsolutePath();
//restart.sh脚本文件
String scriptString = "#! /bin/bash\n" +
"tomcat_home=/usr/local/apache-tomcat-8.5.24\n" +
"SHUTDOWN=$tomcat_home/bin/shutdown.sh\n" +
"STARTTOMCAT=$tomcat_home/bin/startup.sh\n" +
"echo \"准备关闭$tomcat_home\"\n" +
"$SHUTDOWN &\n" +
"\n" +
"#删除tomcat的临时目录\n" +
"rm $tomcat_home/work/* -rf &\n" +
"\n" +
"sleep 5 &\n" +
"echo \"准备启动$tomcat_home\"\n" +
"$STARTTOMCAT\n" +
"#看启动日志\n" +
"#tail -f $tomcat_home/logs/catalina.out";
//将restart.sh写到linux文件夹下
File restart = new File(binPath+"/restart.sh");
FileOutputStream stream = new FileOutputStream(restart);
stream.write(scriptString.getBytes());
stream.flush();
stream.close();
//修改执行脚本权限
String urla = File.separator+"usr"+File.separator+"local"+File.separator+"apache-tomcat-8.5.24"+File.separator+"bin"+File.separator+"restart.sh";
String[] commands = new String[] { "/system/bin/sh", "-c",
"chmod 777 "+urla };
Process process = null;
DataOutputStream dataOutputStream = null;
try {
process = Runtime.getRuntime().exec("su");
dataOutputStream = new DataOutputStream(process.getOutputStream());
int length = commands.length;
for (int i = 0; i < length; i++) {
dataOutputStream.writeBytes(commands[i] + "\n");
}
dataOutputStream.writeBytes("exit\n");
dataOutputStream.flush();
process.waitFor();
//执行脚本,重启服务器
Process proc = Runtime.getRuntime().exec(urla);
proc.waitFor();
} catch (Exception e) {
} finally {
try {
if (dataOutputStream != null) {
dataOutputStream.close();
}
process.destroy();
} catch (Exception e) {
}
}
}