java中 用telnet 判斷服務器遠程端口是否開啟


package net.jweb.common.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Map;

public class UsingProcessBuilder {

    

    public static String getNodeStatuss() {
        
        System.out.println("UsingProcessBuilder.getNodeStatuss()"); 
        String command = "  telnet  192.168.4.200 3306  ";
        command = "cmd /d dir";// ok
        command = "cmd";// ok
        command = "calc";// ok
        command = "telnet";// 不行
        Process process;
        StringBuffer sb = new StringBuffer();
        try {
            
//            Process proc=Runtime.getRuntime().exec("notepad");
            
            process = Runtime.getRuntime().exec(command);
//            InputStream inputStream = process.getInputStream();
//            
//            int read;
//            byte[] b = new byte[1024*1024];
//            while ((read=inputStream.read(b))!=-1) {
//                String str = new String(b);
//                sb.append(str);
//            }
//            inputStream.close();
            
            final InputStream is1 = process.getInputStream();  
            new Thread() {
                public void run() {
                    BufferedReader br = new BufferedReader(new InputStreamReader(is1));  
                    try {  
                        String lineB = null; 
                        while ((lineB = br.readLine()) != null) 
                        {  
                            if (lineB != null)
                                System.out.println(lineB);  
                        }  
                    } catch (IOException e) {  
                        e.printStackTrace();  
                    }  
                }  
            }.start(); 
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }
    
    /**
     * 獲取Windows系統下的網卡的MAC地址
     * 
     * @return
     */
    public static String getPhysicalAddress() {
        Process p = null;
        try {
            // 執行ipconfig /all命令
            // "cmd ", " 192.168.4.200", " 3306"
            // "ipconfig", "/all"
            // p = new ProcessBuilder("ipconfig", "/all").start();
            // p = new ProcessBuilder("telnet", "host 192.168.4.200").start();
            p = Runtime.getRuntime().exec(" telnet  192.168.4.200 3306" );
//            p = new ProcessBuilder("cmd", " dir").start();
        } catch (IOException e) {
            e.printStackTrace();
            return "eeeeeeeee";
        }
        byte[] b = new byte[1024];
        int readbytes = -1;
        StringBuffer sb = new StringBuffer();
        // 讀取進程輸出值
        InputStream in = p.getInputStream();
        try {
            while ((readbytes = in.read(b)) != -1) {
                sb.append(new String(b, 0, readbytes));
            }

        } catch (IOException e1) {
        } finally {
            try {
                in.close();
            } catch (IOException e2) {
            }
        }

        return sb.toString();
    }

    public static void executeMyCommand2() {
        ProcessBuilder pb = null;
        String sysatt = null;
        try {
            // 創建一個進程示例
            pb = new ProcessBuilder("cmd.exe");
            // 獲取系統參數並打印顯示
            Map<String, String> env = pb.environment();
//            Iterator it = env.keySet().iterator();
//            while (it.hasNext()) {
//                sysatt = (String) it.next();
//                System.out.println("System Attribute:" + sysatt + "="
//                        + env.get(sysatt));
//            }
            // 設置工作目錄
            pb.directory(new File("C:\\Windows\\winsxs\\wow64_microsoft-windows-commandprompt_31bf3856ad364e35_6.1.7601.17514_none_f387767e655cd5ab"));
            Process p = pb.start();
            // 將要執行的Windows命令寫入
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(
                    p.getOutputStream()));
            // '/r/n'是必須寫入的
//            bw.write("test.bat /r/n");
            bw.write("ping -t www.baidu.com /r/n");
            // flush()方法是必須調用的
            bw.flush();
            // 將執行結果打印顯示
            InputStream is = p.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "GBK");
            BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 執行自定義的一個命令,該命令放在C:/temp下,並且需要2個環境變量的支持。
     */
    public static boolean executeMyCommand() {
        // 創建系統進程創建器
        ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
        // 獲得進程的環境
        Map<String, String> env = pb.environment();
        // 設置和去除環境變量
        env.put("VAR1", "myValue");
        env.remove("VAR0");
        env.put("VAR2", env.get("VAR1") + ";");
        // 切換工作目錄
        pb.directory(new File("C:/temp"));
        try {
            // 得到進程實例
            Process p = pb.start();
            // 等待該進程執行完畢
            if (p.waitFor() != 0) {
                // 如果進程運行結果不為0,表示進程是錯誤退出的
                // 獲得進程實例的錯誤輸出
                InputStream error = p.getErrorStream();
                // do something
            }
            // 獲得進程實例的標准輸出
            InputStream sdin = p.getInputStream();

        } catch (IOException e) {
        } catch (InterruptedException e) {
        }
        return true;
    }

    public static void main(String[] args) {
         String address = UsingProcessBuilder.getNodeStatuss();

//        executeMyCommand2();

         System.out.println(address);

    }
}

 

如上的代碼, 我想判斷服務器遠程端口是否開啟, 卻一直沒有得到正確的結果。我使用的是telnet , 其他的好像也不行。

執行 telnet 的時候, waitFor()的返回值始終是-1, 讀取p.getInputStream 始終沒有輸出。 Runtime/ ProcessBuilder 其實都是一樣的。

 

后面突然領悟到, telnet其實是打開了子進程進行通話, 其本身沒有任何內容輸出,直接返回了-1。而java的Process  好像沒有辦法獲取其是否成功生成了子進程, 以及子進程的內容。

讀了 http://blog.csdn.net/Code_cj/article/details/6411682 后明白了。 要實現這樣的功能恐怕只有借助第三方的工具:commons-net ----  Jsch

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM