首页 > 技术文章 > Java远程连接linux的方法,执行命令并输出结果

fanpc 2020-08-14 10:53 原文

需要先导入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 ();

推荐阅读