通过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. 第一次安装myeclipse+tomcat经验

    在网上找了很多资料,这里记录一下验证有用的资料,避免以后走弯路 1.安装myeclipse 参考如下URL,亲测有用 https://blog.csdn.net/qingjianduoyun/arti ...

  2. HttpClient 知识点

    1. httpClient 默认超时时间是 60秒 2.httpClient 是模拟表单提交,所以服务端接口要用HttpServletRequest request 接收  例如: request.g ...

  3. centos7 安装php7,报错cannot get uid for user nginx

     

  4. Django的admin管理系统写入中文出错的解决方法/1267 Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and (utf8_general_ci,COERCIBLE) for operation ‘locate’

    Django的admin管理系统写入中文出错的解决方法 解决错误: 1267  Illegal mix of collations (latin1_swedish_ci,IMPLICIT) and ( ...

  5. html5与css3面试题(2)

    10.xhtml与HTML的区别? Html是对web网页设计的语言,而xhtml是基于xml的置标语言 11.面向对象的引用方法分为几种? 内部写的 原型链引用的 12.什么是重载? 函数名相同,但 ...

  6. 2018-2019-2 网络对抗技术 20165305 Exp4 恶意代码分析

    Exp4 恶意代码分析 1.实践目标 1.1是监控你自己系统的运行状态,看有没有可疑的程序在运行. 1.2是分析一个恶意软件,就分析Exp2或Exp3中生成后门软件:分析工具尽量使用原生指令或sysi ...

  7. 2018-2019-2 20165335 《网络对抗技术》 Exp6 信息搜集与漏洞扫描

    1.实践目标 掌握信息搜集的最基础技能与常用工具的使用方法. 2.实践内容 (1)各种搜索技巧的应用 (2)DNS IP注册信息的查询 (3)基本的扫描技术:主机发现.端口扫描.OS及服务版本探测.具 ...

  8. 并查集 P3367 【模板】并查集

    P3367 [模板]并查集 #include<iostream> #include<algorithm> #include<cstdio> #include< ...

  9. jdbc之工具类DBUtil的使用

    首先回顾一下jdbc的使用方法: 1. 注册驱动 2. 建立连接 3. 建立statement 4. 定义sql语句 5. 执行sql语句,如果执行的是查询需遍历结果集 6. 关闭连接 其中建立连接和 ...

  10. latch releae overview

    1. MainFsmStates add MAIN_FSM_LATCH_OPEN_FOR_DOOR_CLOSE 2. mb_PcuTriggerReInit = TRUE; /* start PCU ...