java在linux中执行shell脚本,用telnet检测指定IP的端口是不是可以连接上

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java在linux中执行shell脚本,用telnet检测指定IP的端口是不是可以连接上相关的知识,希望对你有一定的参考价值。

java在linux中执行shell脚本,用telnet检测指定IP的端口是否可以连接上。java中的代码是
String[] cmdA = "/bin/sh", "-c", cmd ;
Process process = Runtime.getRuntime().exec(cmdA);
然后获取process的流来分析结果。
如果用"ping 192.168.1.3 -c 10"作为cmd传入时,能得到返回的结果。

我用"telnet 192.168.1.3 8090"作为cmd传入时,服务器那边运行会直接进入telnet了,没有返回结果。
求得大神指导下,要在telnet命令后加什么参数还是怎么做,才能让telnet尝试连接得到连接是否成功的结果后直接断开并返回结果。

参考技术A 你可以增加两个进程,一个用来监视telnet的输出,另外一个用来监视是不是有错。你分析那个telnet的输出就好了。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
public class ExcuteThread extends Thread
private String name;
public ExcuteThread(String name)
this.name = name;

@Override
public void run()
try
Process p = Runtime.getRuntime().exec(name);
InputStream fis = p.getInputStream();
final BufferedReader brError = new BufferedReader(
new InputStreamReader(p.getErrorStream(), "gb2312"));
InputStreamReader isr = new InputStreamReader(fis, "gb2312");
final BufferedReader br = new BufferedReader(isr);
Thread t1 = new Thread()
public void run()
String line = null;
try
while ((line = brError.readLine()) != null)
// System.out.println(line);

catch (IOException e)
e.printStackTrace();
finally
try
if (brError != null)
brError.close();
catch (IOException e)
e.printStackTrace();



;
Thread t2 = new Thread()
public void run()
String line = null;
try
while ((line = br.readLine()) != null)
System.out.println(line);

catch (IOException e)
e.printStackTrace();
finally
try
if (br != null)
br.close();
catch (IOException e)
// TODO Auto-generated catch block
e.printStackTrace();



;
t1.start();
t2.start();
catch (IOException e1)
// TODO Auto-generated catch block
e1.printStackTrace();
finally


追问

呃,我要的不是这个java代码,是shell命令,执行telnet会直接进入telnet连接了,所以一直收不到到返回结果,我是想在命令里加什么可以让它连接后返回结果。

追答

我的意思就是你获得telnet执行的信息,比如下面就是telnet 127.0.0.1的信息。
Trying 127.0.0.1…

Connected to serve. somewhere. com.

Escape character is '?]'.

“TurboLinux release 4. 0 (Colgate)

kernel 2.0.18 on an I486 

追问

呃,问题就是获取不到啊,因为命令执行进去了没出来,没有返回结果。

以上是关于java在linux中执行shell脚本,用telnet检测指定IP的端口是不是可以连接上的主要内容,如果未能解决你的问题,请参考以下文章

怎么用java代码调用远程Linux上的shell脚本

使用java中的jsch在linux中通过sudo命令执行shell脚本以启动服务

shell 在脚本中执行了source /etc/profile 不生效

linux shell脚本换行问题

如何在shell中执行一个模块,这个模块需要传入参数

Java基础知识java调用并执行shell脚本