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;
    }

}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值