Java 通过ssh连接lunix,执行语句

这里总结两种方法。

第一种方法:Ganymed SSH-2 for Java是一个纯Java实现的SHH2库,官网为http://www.ganymed.ethz.ch/ssh2/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;


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

public class SshCommandExcute {

    /**
     * 运行命令
     * 
     * @param command
     *            命令
     * @return
     */
    public String run(String command) {
        String hostname = "127.0.0.1";
        int port = 22;
        String username = "root";
        String password = "root";
        // 指明连接主机的IP地址
        Connection conn = new Connection(hostname,port);
        Session ssh = null;
        String result = "";
        try {
            // 连接到主机
            conn.connect();
            // 使用用户名和密码校验
            boolean isconn = conn.authenticateWithPassword(username, password);
            if (!isconn) {
                System.out.println("用户名称或者是密码不正确");
            } else {
                System.out.println("已经连接OK");
                ssh = conn.openSession();
                ssh.execCommand(command);
                InputStream is = new StreamGobbler(ssh.getStdout());
                BufferedReader brs = new BufferedReader(new InputStreamReader(is, "UTF-8"));
                while (true) {
                    // System.out.println(brs.readLine());
                    String line = brs.readLine();
                    if (line == null) {
                        break;
                    }
                    result += line + "\r\n";
                }
            }
            // 连接的Session和Connection对象都需要关闭
            ssh.close();
            conn.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] arg) {
        String command = "ls;hadoop fs -ls /";
        String line = new SshCommandExcute().run(command);
        System.out.println(line);
    }

}

第二种方法:JSch是ssh2的一个纯Java实现。它允许你连接到一个sshd 服务器,使用端口转发,X11转发,文件传输等等。官网:http://www.jcraft.com/jsch/

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Properties;

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.opensymphony.xwork2.Result;

public class SSHConnect {

    /**
     * @param args
     */
    public static void main(String[] args) {

    }
    public static String SSHConnectAndExecute(String cmd)
    {
        Session session=null;
        ChannelExec channelExec=null;
         BufferedReader reader=null;
         String result="";
        try {
            JSch jsch = new JSch(); // 创建JSch对象  
            String hostname = "127.0.0.1";
            int port = 22;
            String username = "root";
            String password = "root";

            session = jsch.getSession(username, hostname, port); // 根据用户名,主机ip,端口获取一个Session对象  
            session.setPassword(password); // 设置密码  
            Properties config = new Properties();  
            config.put("StrictHostKeyChecking", "no");  
            session.setConfig(config); // 为Session对象设置properties  
            int timeout = 600000000;  
            session.setTimeout(timeout); // 设置timeout时间  
            session.connect(); // 通过Session建立链接  
            channelExec = (ChannelExec) session.openChannel("exec");  
            channelExec.setCommand(cmd);  
            channelExec.setInputStream(null);  
            channelExec.setErrStream(System.err);  
            channelExec.connect();  
            InputStream in = channelExec.getInputStream();  
            reader = new BufferedReader(new InputStreamReader(in, Charset.forName("UTF-8")));  
            String buf = null;  

            StringBuffer sb = new StringBuffer();  
            while ((buf = reader.readLine()) != null) {  
                sb.append(buf);  
                result+=buf+"\r\n";
                System.out.println(buf);// 打印控制台输出  
            }  



        } catch (Exception e) {
            // TODO: handle exception
        }finally{
              if (null != session) {  
                    session.disconnect();  
                }  
             try {
                reader.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }  
             channelExec.disconnect();  
        }
        return result;
    }

}

你可能感兴趣的:(java)