阅读更多
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.SocketException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.net.telnet.TelnetClient;
public class PingTelnetUtil {
public static void main(String[] args) {
System.out.println(testTelnet("1.4.2.1", 22));
// System.out.println(testPing("1.2.2.1"));
}
public static String testTelnet(String ip, Integer port) {
try {
TelnetClient telnetClient = new TelnetClient("vt200"); // 指明Telnet终端类型,否则会返回来的数据中文会乱码
telnetClient.setDefaultTimeout(5000); // socket延迟时间:5000ms
telnetClient.connect(ip, port);
telnetClient.disconnect();
return "telnet通";
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "telnet不通";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "telnet不通";
}catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "telnet不通";
}
}
public static String testPing(String ip) {
InputStream is = null;
InputStreamReader isr = null;
BufferedReader brStat = null;
try {
Process process = Runtime.getRuntime().exec("ping " + ip);
is = process.getInputStream();
isr = new InputStreamReader(is, "gbk");
brStat = new BufferedReader(isr);
String result = "连接异常";
String temp = "";
while ((temp = brStat.readLine()) != null) {
if(StringUtils.isBlank(temp)){
continue;
}
if (temp.indexOf("时间") > -1) {
result = "ping通";
break;
}
if (temp.indexOf("请求超时") > -1) {
result = "请求超时";
break;
}
}
return result;
} catch (SocketException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "连接异常";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "连接异常";
} finally {
try {
is.close();
isr.close();
brStat.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}