ch.ethz.ssh2.Session和com.jcraft.jsch.Session
通过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的更多相关文章
- ssh com.jcraft.jsch.JSchException: Algorithm negotiation fail报错问题解决
我司自动安装部署工具ideploy,使用ssh连接主机并部署业务.今天提供给一线安装规划后,安装报错,测试连接主机失败,而直接使用ssh是可以连接上主机的.查看问题错误堆栈如下: ERROR pool ...
- com.jcraft.jsch.JSchException: Auth fail
背景 服务器信息: 服务器A:10.102.110.1 服务器B:10.102.110.2 需要从服务器A通过Sftp传输文件到服务器B. 应用项目中有一个功能,要通个关Sftp进行日志文件的传输,在 ...
- Java中com.jcraft.jsch.ChannelSftp讲解
http://blog.csdn.net/allen_zhao_2012/article/details/7941631 http://www.cnblogs.com/longyg/archive/2 ...
- Hadoop 之 高可用不自动切换(ssh密钥无效 Caused by: com.jcraft.jsch.JSchException: invalid privatekey )
案例 在安装hadoop ha之后,验证HDFS高可用时,怎么都不能实现自动切换.查看zkfc日志发现错误信息如下: WARN org.apache.hadoop.ha.SshFenceByTcpPo ...
- 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 ...
- 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 ...
- session机制详解以及session的相关应用
session是web开发里一个重要的概念,在大多数web应用里session都是被当做现成的东西,拿来就直接用,但是一些复杂的web应用里能拿来用的session已经满足不了实际的需求,当碰到这样的 ...
- [转]session 持久化问题(重启服务器session 仍然存在)
转:http://xiaolongfeixiang.iteye.com/blog/560800 关于在线人数统计,大都使用SessionListener监听器实现. SessionListener 触 ...
- securtcrt session配置转xshell的session配置
参数: 1.securtcrt的session目录 2.一个xshell的模版文件 3.输出目录(必须不存在,自动创建) #!/usr/bin/python # -*- coding:utf-8 -* ...
随机推荐
- XGBoost 与 Boosted Tree
http://www.52cs.org/?p=429 作者:陈天奇,毕业于上海交通大学ACM班,现就读于华盛顿大学,从事大规模机器学习研究. 注解:truth4sex 编者按:本文是对开源xgboo ...
- 畅捷通T+12.2升级时发生的错误及处理方法图解
前言:最近处理一个客户单位的财务数据,需要从2004年的U820版本的数据升级到畅捷通T+12.2版本.经查,该升级先要将原数据升级到T6,再从T6升级到畅捷通T+12.2版本.U820升级到T6很简 ...
- Oracle 体系结构chapter2
前言:Oracle 体系结构其实就是指oracle 服务器的体系结构,数据库服务器主要由三个部分组成 管理数据库的各种软件工具(sqlplus,OEM等),实例(一组oracle 后台进程以及服务器中 ...
- Asp.Net Core WebApi 和Asp.Net WebApi上传文件
public class UpLoadController : ControllerBase { private readonly IHostingEnvironment _hostingEnviro ...
- Linux 磁盘挂载分区
举例说明: 新增磁盘的设备文件名为 /dev/vdb 大小为100GB. #fdisk -l 查看新增的的磁盘 1.对新增磁盘进行分区 #fdisk /dev/vdb 按提示操作 p打印 n新增 d ...
- Java面试题整理---网络篇
1.BIO.AIO和NIO的概念及区别? 2.什么是长连接和短连接? 3.http1.0.http1.1和http2.0的区别? 4.https和http的区别? 5.https的工作原理? ...
- Web前端培训教程:CSS3动画怎么实现的
动画 CSS3属性中有关于制作动画的三个属性: transform,transition,animation keyframes @keyframes mymove{ from{初始状态属性} to{ ...
- mysql,jdbc、连接池
show processlist; select * from information_schema.processlist; Command: The type of command the thr ...
- @Conditional 原理
1,这里讲的是:org.springframework.context.annotation.Conditional 2,在springConfig文件里注册bean @Conditional(Col ...
- pandas替换一列中的汉字为数字
表格的一列“总金额”应该全部为数字,但其中少数项出现汉字,应该将汉字替换为数字,才能进行后面的计算. 先定义一个函数: def is_number(s): try: float(s) return T ...