package com.kedacom.ics.utils;
import com.kedacom.ics.core.exception.BusinessException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.InputStreamReader;
/**
* ssh服务的开启和关闭
* @author wangshuxuan
* @date 2018/12/11 14:03
*/
public class SSHOperate {
private static Logger logger = LoggerFactory.getLogger(SSHOperate.class);
/**
* 获取ssh状态
*/
public static boolean sshStatus(){
//ssh状态
boolean bOpen = false;
try {
Runtime runtime = Runtime.getRuntime();
//获取当前操作系统
String systemName = System.getProperty("os.name").toLowerCase();
//命令
String strCmd = "";
if (systemName.startsWith("win")) {
//win下无ssh服务(仅作测试)
strCmd = "cmd /c net start | findstr Redis";
} else {
strCmd = " service sshd status";
}
//Process执行外部命令
BufferedReader bufferedReader = null;
if (!strCmd.isEmpty()) {
Process process = runtime.exec(strCmd);
InputStreamReader inputStreamReader = new InputStreamReader(process.getInputStream(), "utf8");
bufferedReader = new BufferedReader(inputStreamReader);
process.waitFor();
}
if (bufferedReader != null) {
String line;
while ((line = bufferedReader.readLine()) != null) {
if (line.contains("active") && line.contains("running")) {
logger.info("获取ssh状态成功!");
bOpen = true;
break;
}
}
} else {
logger.info("获取ssh状态失败!");
}
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException("获取ssh状态失败!");
}
return bOpen;
}
/**
* ssh开关
* @param type
*/
public static boolean sshChange(String type){
//ssh设置结果
boolean bSetting = false;
try {
Runtime runtime = Runtime.getRuntime();
//获取当前操作系统
String systemName = System.getProperty("os.name").toLowerCase();
//命令
String strCmd = "";
if (systemName.startsWith("win")) {
//win下无ssh服务(仅作测试)
strCmd = "cmd /c pkgmgr /iu:”TelnetClient”";
} else {
if (type.equals("on")) {
strCmd = " service sshd start";
} else {
strCmd = " service sshd stop";
}
}
//Process执行外部命令
if (!strCmd.isEmpty()) {
Process process = runtime.exec(strCmd);
process.waitFor();
//判断设置的结果
boolean bTmp = sshStatus();
if ((type.equals("on") && bTmp) ||
(type.equals("off") && !bTmp)) {
bSetting = true;
logger.info("设置ssh成功!");
} else {
logger.info("设置ssh失败!");
}
}
} catch (Exception e) {
e.printStackTrace();
throw new BusinessException("设置ssh失败!");
}
return bSetting;
}
public static void main(String[] args) throws Exception {
//sshStatus();
sshChange("on");
}
}
ssh服务的开启和关闭
猜你喜欢
转载自blog.csdn.net/qq_38999810/article/details/84981999
今日推荐
周排行