测试ping和telnet 工具类

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();
}
}
}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值