通过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. 【转】Install Win32 OpenSSH (test release)

    Openssh download url:https://github.com/PowerShell/Win32-OpenSSH/releases Install instruction: Insta ...

  2. 使用StringEscapeUtils转义、反转义字符串

    使用commmons-lang.jar中的字符串转义工具类org.apache.commons.lang.StringEscapeUtils转义.反转义字符串,支持CSV.HTML.JAVA.Java ...

  3. AI时代学习新的技术,方向为计算机视觉--欢迎来我的简书blog拔草

    2017-09-01 19:29:33 简书blog: https://www.jianshu.com/u/973c8c406de7

  4. Linux代理服务器—squid正向代理实验

    1.代理服务器squid简介 Squid cache(简称为Squid)是一个流行的自由软件(GNU通用公共许可证)的代理服务器和Web缓存服务器.Squid有广泛的用途,从作为网页服务器的前置cac ...

  5. 火狐开发----如何快速的安装火狐XPI文件

    第一步:火狐的自动安装扩展程序,https://addons.mozilla.org/zh-CN/firefox/addon/autoinstaller/ 第二步:安装wget工具,这个Linux应该 ...

  6. Maven Webapp项目web.xml版本记录

    web.xml 2.0版本 <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3// ...

  7. js 计算两个时间戳之间相隔天数

    var start=1491789600000;//2017-4-10 10:00 var end=1494381600000;//2017-5-10 10:00 var utc=end-start; ...

  8. vue-cli配置

    转载--https://www.cnblogs.com/caideyipi/p/8187656.html 手撕vue-cli配置文件——config篇   最近一直在研究webpack,突然想看看vu ...

  9. 1.2:Properties

    文章著作权归作者所有.转载请联系作者,并在文中注明出处,给出原文链接. 本系列原更新于作者的github博客,这里给出链接. 上一节我们了解了一个Shader的基本结构,这一节,我们从 Propert ...

  10. HTTP 400错误--请求无效

    在发送请求后台数据时会报出来HTTP400错误,请求无效,出现这个请求无效报错说明请求没有进入到后台服务里 原因:1.前端提交数据的字段名称或者是字段类型和后台的实体类不一致.导致无法封装 2.前端提 ...