通过Jsch连接
step 1引入jar包
<!-- jcraft包 -->
        <dependency>
            <groupId>com.jcraft</groupId>
            <artifactId>jsch</artifactId>
            <version>0.1.53</version>
        </dependency>

step 2 代码
import java.io.InputStream;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

public class Main {
    public static void main(String[] args) throws Exception {
        long currentTimeMillis = System.currentTimeMillis();

String command = "uname -a";
 
        JSch jsch = new JSch();
        Session session = jsch.getSession("xfraud", "192.168.115.64", 22);
        session.setPassword("cfca1234");
        session.setConfig("StrictHostKeyChecking", "no");
        session.connect(60 * 1000);
        Channel channel = session.openChannel("exec");
        ((ChannelExec) channel).setCommand(command);
 
        channel.setInputStream(null);
 
        ((ChannelExec) channel).setErrStream(System.err);
 
        InputStream in = channel.getInputStream();
 
        channel.connect();
 
        byte[] tmp = new byte[1024];
        while (true) {
            while (in.available() > 0) {
                int i = in.read(tmp, 0, 1024);
                if (i < 0) break;
                System.out.print(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                if (in.available() > 0) continue;
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
            }
        }
        channel.disconnect();
        session.disconnect();
 
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("Jsch方式"+(currentTimeMillis1-currentTimeMillis));
    }

}

通过ganymed-ssh2连接
step 1 引入jar包
<dependency>
            <groupId>ch.ethz.ganymed</groupId>
            <artifactId>ganymed-ssh2</artifactId>
            <version>build210</version>

</dependency>

step 2 代码

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;

//import org.apache.commons.lang.StringUtils;

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

public class MainCommand {
    private static String DEFAULTCHART = "UTF-8";

private static Connection login(String ip, String username, String password) {
        boolean flag = false;
        Connection connection = null;
        try {
            connection = new Connection(ip);
            connection.connect();// 连接
            flag = connection.authenticateWithPassword(username, password);// 认证
            if (flag) {
                System.out.println("================登录成功==================");
                return connection;
            }
        } catch (IOException e) {
            System.out.println("=========登录失败=========" + e);
            connection.close();
        }
        return connection;
    }

/**
     * 远程执行shll脚本或者命令
     * 
     * @param cmd
     *            即将执行的命令
     * @return 命令执行完后返回的结果值
     */
    private static String execmd(Connection connection, String cmd) {
        String result = "";
        try{
            if (connection != null) {
                Session session = connection.openSession();// 打开一个会话
                session.execCommand(cmd);// 执行命令
                result = processStdout(session.getStdout(), DEFAULTCHART);
                System.out.println(result);
                // 如果为得到标准输出为空,说明脚本执行出错了
                /*if (StringUtils.isBlank(result)) {
                    System.out.println("得到标准输出为空,链接conn:" + connection + ",执行的命令:" + cmd);
                    result = processStdout(session.getStderr(), DEFAULTCHART);
                } else {
                    System.out.println("执行命令成功,链接conn:" + connection + ",执行的命令:" + cmd);
                }*/
                connection.close();
                session.close();
            }
        } catch (IOException e) {
            System.out.println("执行命令失败,链接conn:" + connection + ",执行的命令:" + cmd + "  " + e);
            e.printStackTrace();
        }
        return result;

}

/**
     * 解析脚本执行返回的结果集
     * 
     * @param in
     *            输入流对象
     * @param charset
     *            编码
     * @return 以纯文本的格式返回
     */
    private static String processStdout(InputStream in, String charset) {
        InputStream stdout = new StreamGobbler(in);
        StringBuffer buffer = new StringBuffer();
        ;
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(stdout, charset));
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line + "\n");
                System.out.println(line);
            }
            br.close();
        } catch (UnsupportedEncodingException e) {
            System.out.println("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("解析脚本出错:" + e.getMessage());
            e.printStackTrace();
        }
        return buffer.toString();
    }

public static void main(String[] args) {
        long currentTimeMillis = System.currentTimeMillis();
        String ip = "192.168.115.64";
        String username = "xfraud";
        String password = "cfca1234";
        String cmd = "uname -a";        
        Connection connection = login(ip, username, password);
        String execmd = execmd(connection, cmd);
        System.out.println(execmd);
        long currentTimeMillis1 = System.currentTimeMillis();
        System.out.println("ganymed-ssh2方式"+(currentTimeMillis1-currentTimeMillis));
    }
}

转载:https://blog.csdn.net/u011937566/article/details/81666347

ch.ethz.ssh2.Session和com.jcraft.jsch.Session的更多相关文章

  1. ssh com.jcraft.jsch.JSchException: Algorithm negotiation fail报错问题解决

    我司自动安装部署工具ideploy,使用ssh连接主机并部署业务.今天提供给一线安装规划后,安装报错,测试连接主机失败,而直接使用ssh是可以连接上主机的.查看问题错误堆栈如下: ERROR pool ...

  2. com.jcraft.jsch.JSchException: Auth fail

    背景 服务器信息: 服务器A:10.102.110.1 服务器B:10.102.110.2 需要从服务器A通过Sftp传输文件到服务器B. 应用项目中有一个功能,要通个关Sftp进行日志文件的传输,在 ...

  3. Java中com.jcraft.jsch.ChannelSftp讲解

    http://blog.csdn.net/allen_zhao_2012/article/details/7941631 http://www.cnblogs.com/longyg/archive/2 ...

  4. Hadoop 之 高可用不自动切换(ssh密钥无效 Caused by: com.jcraft.jsch.JSchException: invalid privatekey )

    案例 在安装hadoop ha之后,验证HDFS高可用时,怎么都不能实现自动切换.查看zkfc日志发现错误信息如下: WARN org.apache.hadoop.ha.SshFenceByTcpPo ...

  5. com.jcraft.jsch.JSchException: java.io.FileNotFoundException: file:\D:\development\ideaProjects\salary-card\target\salary-card-0.0.1-SNAPSHOT.jar!\BOOT-INF\classes!\keystore\login_id_rsa 资源未找到

    com.jcraft.jsch.JSchException: java.io.FileNotFoundException: file:\D:\development\ideaProjects\sala ...

  6. Unable to make the session state request to the session state server处理

    Server Error in '/' Application. Unable to make the session state request to the session state serve ...

  7. session机制详解以及session的相关应用

    session是web开发里一个重要的概念,在大多数web应用里session都是被当做现成的东西,拿来就直接用,但是一些复杂的web应用里能拿来用的session已经满足不了实际的需求,当碰到这样的 ...

  8. [转]session 持久化问题(重启服务器session 仍然存在)

    转:http://xiaolongfeixiang.iteye.com/blog/560800 关于在线人数统计,大都使用SessionListener监听器实现. SessionListener 触 ...

  9. securtcrt session配置转xshell的session配置

    参数: 1.securtcrt的session目录 2.一个xshell的模版文件 3.输出目录(必须不存在,自动创建) #!/usr/bin/python # -*- coding:utf-8 -* ...

随机推荐

  1. 【论文速读】Cong_Yao_CVPR2017_EAST_An_Efficient_and_Accurate_Scene_Text_Detector

    Cong_Yao_CVPR2017_EAST_An_Efficient_and_Accurate_Scene_Text_Detector 作者和代码 非官方版tensorflow实现 非官方版kera ...

  2. sitecore8.2 如何关闭性能计数器

    在Sitecore.config文件或补丁文件修改Counters.Enabled为false值,此key默认为true;然后再修改Sitecore.Tasks.CounterDumpAgent 时间 ...

  3. C# 弹出确定、取消窗口

    if (MessageBox.Show("确定要退出吗?", "", MessageBoxButtons.OKCancel, MessageBoxIcon.Qu ...

  4. jQuery常见用法

    jQuery有好多版本本,无法同时引用两个不同的版本,容易造成混乱,用哪一个,调用哪一个.\ jQuery引用到<head></head>中,页面加载时就需要特效调用这些方法. ...

  5. WindowsService调用API

    本文着重于WindowsServic如何调用API以及出现部分问题的解决方案 本文Windows Service 创建摘自JasperXu的博客   链接:http://www.cnblogs.com ...

  6. MySQL_ALTER命令

    当我们需要修改数据表名或者修改数据表字段时,就需要使用到MySQL ALTER命令. 1)修改表名:表名可以在数据库中唯一标识一个table 命令格式:ALTER TABLE 旧名 RENAME 新名 ...

  7. jquery判断点击事件是否指定区域

    $(document).click(function(e){  e = window.event || e; // 兼容IE7 obj = $(e.srcElement || e.target);   ...

  8. ASUS RT-N16 使用OpenWrt 安装 ss记录

    本文用于记录一下使用ASUS RT-N16 使用OpenWrt 安装 shadowsocks的过程. 前后一共折腾了一个星期,原先使用的是tomato固件,但是在配置iptables的过程中,执行 r ...

  9. Python Iterables Iterators Generators

    container 某些对象包含其它对象的引用,这个包含其它对象引用的对象叫容器.例如list可以包含int对象,或者由其它数据类型(或数据结构)的对象组成一个list. 对其他对象的引用是容器值的一 ...

  10. C# readonly与const区别

    静态常量:是指编译器在编译时候会对常量进行解析,并将常量的值替换成初始化的那个值. 动态常量的值则是在运行的那一刻才获得的,编译器编译期间将其标示为只读常量,而不用常量的值代替,这样动态常量不必在声明 ...