JSch SSH2 for Java

参考

https://www.jianshu.com/p/ede91b0b8495

依赖

com.jcraft jsch 0.1.55

代码

package com.controller;
import java.io.BufferedReader;
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;

public class ssh2 {
public static void main(String[] args) throws Exception {
JSch jsch = new JSch(); // 创建JSch对象
String userName = “root”;// 用户名
String password = “111111”;// 密码
String host = “192.168.3.157”;// 服务器地址
int port = 22;// 端口号
String cmd = "yum install screen -y ";// 要运行的命令
Session session = jsch.getSession(userName, host, port); // 根据用户名,主机ip,端口获取一个Session对象
session.setPassword(password); // 设置密码
Properties config = new Properties();
config.put(“StrictHostKeyChecking”, “no”);
session.setConfig(config); // 为Session对象设置properties
int timeout = 60000000;
session.setTimeout(timeout); // 设置timeout时间
session.connect(); // 通过Session建立链接
ChannelExec channelExec = (ChannelExec) session.openChannel(“exec”);
channelExec.setCommand(cmd);
channelExec.setInputStream(null);
channelExec.setErrStream(System.err);
channelExec.connect();
InputStream in = channelExec.getInputStream();
BufferedReader 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);
System.out.println(buf);// 打印控制台输出
}
reader.close();
channelExec.disconnect();
if (null != session) {
session.disconnect();
}
}
}

JSch远程执行shell命令的两种方法

https://www.qycn.com/xzx/article/2487.html
exec通道和shell通道之间重要的区别:shell通道将建立shell环境,例如环境变量,而exec通道则不会。
对于ChannelShell,输入流提供这些命令的命令和输入。这就像在本地计算机上使用交互式shell一样。 (它通常仅用于此:交互式使用。)
对于ChannelExec,命令被给予与connect()之前set命令(),并且将输入流将被发送到这些命令作为输入。 (大多数情况下,你将有只有一个命令,但您可以提供使用正常的外壳分离&,&&,|,||,;,换行,复合命令多的。)这就像在本地计算机上执行的shell脚本。 (当然,如果其中一个命令本身是交互式shell,则其行为类似于ChannelShell。)
还有第三个类似的,ChannelSubsystem,它执行ssh服务器的子系统 - 这里服务器的配置决定做什么,而不是远程用户的shell。 (最常用的子系统是sftp,但为此,JSch提供了一个了解协议的专用通道。)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值