Java遠程連接linux的方法,執行命令並輸出結果


需要先導入ssh bulid包,方法如下:

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public String execute(String ip, String cmd) {
        String username = "root";
        String password = "password";

        try {
            // 創建連接
            Connection conn = new Connection ( ip, 22 );
            // 啟動連接
            conn.connect ();
            // 驗證用戶密碼
            conn.authenticateWithPassword ( username, password );
            Session session = conn.openSession ();
            //執行命令
            session.execCommand ( cmd );

            InputStream stdout = new StreamGobbler ( session.getStdout () );
            BufferedReader br = new BufferedReader ( new InputStreamReader ( stdout ) );
            StringBuffer buffer = new StringBuffer ();
            String line;
            
            while ((line = br.readLine ()) != null) {
                buffer.append ( line + "\n" );
            }
            
            String result = buffer.toString ();
            
            session.close ();
            conn.close ();
            //如果沒有異常,返回結果為命令執行結果,如果有異常,返回null
            return result;

        } catch (IOException e) {
            e.printStackTrace ();
            return null;
        }

    }

也可以把redline()讀取換成read(),從一行行讀取變成按字符讀取:

InputStream stdout = new StreamGobbler ( session.getStdout () );
StringBuffer buffer = new StringBuffer ();
byte[] bs = new byte[1024 * 16];

 while(true) {
           int count = stdout.read(bs);
           if(count == -1) {
                  break;
            } else {
                    buffer.append(new String(bs, 0, count));
                }
            }
            stdout.close();
            String result = buffer.toString ();


免責聲明!

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



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