java实现Linux环境下ping命令并返回数据,telnet端口检测命令,ssh命令
一.ping命令,并返回数据(linux)
public SysDiagnosticToolVo ping(String ip) {
SysDiagnosticToolVo sysDiagnosticToolVo = new SysDiagnosticToolVo();
String result = null;
if (ip == null || ip.length() <= 0) {
sysDiagnosticToolVo.setPingData("请输入ip地址");
return sysDiagnosticToolVo;
}
BufferedReader br = null;
try {
Process ps = Runtime.getRuntime().exec("ping -c 4 "+ ip);
br = new BufferedReader(new InputStreamReader(ps.getInputStream(), Charset.forName("GBK")));
StringBuilder sb = new StringBuilder();
String line;
while ((line = br.readLine()) != null) {
sb.append(line).append("\n");
}
result = sb.toString();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
sysDiagnosticToolVo.setIp(ip);
sysDiagnosticToolVo.setPingData(result);
return sysDiagnosticToolVo;
}
二.telnet端口检测命令
final Integer timeout = 200;
public String telnet(SysDiagnosticToolDto sysDiagnosticToolDto) {
String result = null;
String ip = sysDiagnosticToolDto.getIp();
Integer port = sysDiagnosticToolDto.getPort();
if (ip == null || ip.length() <= 0 || port == null) {
return null;
}
try (Socket socket = new Socket()) {
socket.connect(new InetSocketAddress(ip, port), timeout);
result =ip +":"+ port + "端口通";
} catch (IOException e) {
e.printStackTrace();
result =ip +":"+ port + "端口不通";
}
return result;
}
三.ssh命令
public String ssh(SysDiagnosticToolDto sysDiagnosticToolDto) {
String ip = sysDiagnosticToolDto.getIp();
Integer port = sysDiagnosticToolDto.getPort();
String userName = sysDiagnosticToolDto.getUserName();
String password = sysDiagnosticToolDto.getPassword();
String result;
if (ip == null || ip.length() <= 0 || port == null) {
return null;
}
if (port != 22) {
result = "端口号错误";
return result;
}
JSch jSch = new JSch();
try {
Session session = jSch.getSession(userName, ip, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(3000);
result = "登录成功";
} catch (JSchException e) {
result = "登录失败";
e.printStackTrace();
}
return result;
}
四.相关jar包
<!--telnet与ssh命令需要的jar包-->
<dependency>
<groupId>com.jcraft</groupId>
<artifactId>jsch</artifactId>
<version>0.1.55</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.7</version>
</dependency>