关键依赖:jsch-0.1.54.jar
/**
* 使用用户名和密码连接
*/
@Test
public void test1() throws JSchException {
//创建一个ssh通讯核心类
JSch jSch = new JSch();
//传主机、端口、用户名获得一个会话
Session session = jSch.getSession("admin", "your host", 22);
//不进行严格模式检查
Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
//设置密码
session.setPassword("your password");
session.setConfig(config);
//连接会话
session.connect();
log.debug("是否连接:" + session.isConnected());
log.debug("会话:" + session);
//断开连接
session.disconnect();
log.debug("是否连接:" + session.isConnected());
}
/**
* 使用用户名和私钥连接
* @throws JSchException
*/
@Test
public void test2() throws JSchException {
//创建一个ssh通讯核心类
JSch jSch = new JSch();
//设置私钥路径
jSch.addIdentity("D:\\hehui\\jsch\\admin_private.ppk");
//传主机、端口、用户名获得一个会话
Session session = jSch.getSession("admin", "your host", 22);
//不进行严格模式检查
Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
session.setConfig(config);
//连接会话
session.connect();
log.debug("是否连接:" + session.isConnected());
log.debug("会话:" + session);
//断开连接
session.disconnect();
log.debug("是否连接:" + session.isConnected());
}
/**
* 远程执行命令
* @throws JSchException
* @throws IOException
*/
@Test
public void test3() throws JSchException, IOException {
log.debug("会话:\r\n" + session);
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
channelExec.setCommand("df -h");
channelExec.connect();
InputStream inputStream = channelExec.getInputStream();
//命令执行结果
String result = IOUtils.toString(inputStream);
log.debug("执行结果:\r\n" + result);
}
/**
* 文件上传
*/
@Test
public void test4() {
try {
//使用ssh会话开启一个sftp文件传输的通道,Channel为抽象类
Channel channel = session.openChannel("sftp");
//强转为ChannelSftp
ChannelSftp channelSftp = (ChannelSftp) channel;
//连接该通道
channelSftp.connect();
String filePath = "D:\\hehui\\jsch\\apache-tomcat-9.0.35.tar.gz";
String fileName = "apache-tomcat-9.0.35.tar.gz";
//服务文件夹路径,只支持绝对路径
String serverDir = "/home/admin/jsch/";
AtomicReference<String> dir = new AtomicReference<>("/");
Stream.of(serverDir.split("\\/")).forEach(p -> {
try {
if (StringUtils.isNotEmpty(p)) {
String existDir = dir.get();
if (StringUtils.equals(existDir,"/")) {
dir.set(existDir + p);
} else {
dir.set(existDir + "/" + p);
}
channelSftp.cd(dir.get());
}
} catch (SftpException e1) {
log.debug("创建目录:" + p);
try {
channelSftp.mkdir(dir.get());
channelSftp.cd(dir.get());
} catch (SftpException e2) {
log.error("error:",e2);
throw new RuntimeException(e2);
}
}
});
FileInputStream in = new FileInputStream(filePath);
//上传
channelSftp.put(in,fileName);
//关闭传输通道
channelSftp.disconnect();
} catch (JSchException e) {
log.error("error",e);
} catch (FileNotFoundException e) {
log.error("error:",e);
} catch (SftpException e) {
log.error("error",e);
}
}
/**
* 文件下载
*/
@Test
public void test5(){
try {
//使用ssh会话开启一个sftp文件传输的通道,Channel为抽象类
Channel channel = session.openChannel("sftp");
//强转为ChannelSftp
ChannelSftp channelSftp = (ChannelSftp) channel;
//连接该通道
channelSftp.connect();
String serverDir = "/home/admin/jsch/";
String serverFile = "apache-tomcat-9.0.35.tar.gz";
FileOutputStream out = new FileOutputStream("D:\\hehui\\jsch\\apache-tomcat-9.0.35_download.tar.gz");
channelSftp.cd(serverDir);
channelSftp.get(serverFile,out);
//关闭通道
channelSftp.disconnect();
} catch (JSchException e) {
log.error("error:",e);
} catch (FileNotFoundException e) {
log.error("error:",e);
} catch (SftpException e) {
log.error("error:",e);
}
}
全部Demo
package com.day0707;
import com.jcraft.jsch.*;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.util.Properties;
import java.util.concurrent.atomic.AtomicReference;
import java.util.stream.Stream;
/**
* JSch(java ssh channel)java连接ssh服务示例
* 远程执行命令、上传、下载
* @author hehui
* @date 2020/7/7
*/
public class JSchDemo {
private Logger log = LoggerFactory.getLogger(this.getClass());
private Session session = null;
@Before
public void open() throws JSchException {
log.debug("开启会话");
//创建一个ssh通讯核心类
JSch jSch = new JSch();
//设置私钥路径
jSch.addIdentity("D:\\hehui\\jsch\\admin_private.ppk");
//传主机、端口、用户名获得一个会话
Session session = jSch.getSession("admin", "your host", 22);
//不进行严格模式检查
Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
session.setConfig(config);
//连接会话
session.connect();
this.session = session;
}
@After
public void close(){
log.debug("关闭会话");
//关闭连接
this.session.disconnect();
}
/**
* 使用用户名和密码连接
*/
@Test
public void test1() throws JSchException {
//创建一个ssh通讯核心类
JSch jSch = new JSch();
//传主机、端口、用户名获得一个会话
Session session = jSch.getSession("admin", "your host", 22);
//不进行严格模式检查
Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
//设置密码
session.setPassword("your password");
session.setConfig(config);
//连接会话
session.connect();
log.debug("是否连接:" + session.isConnected());
log.debug("会话:" + session);
//断开连接
session.disconnect();
log.debug("是否连接:" + session.isConnected());
}
/**
* 使用用户名和私钥连接
* @throws JSchException
*/
@Test
public void test2() throws JSchException {
//创建一个ssh通讯核心类
JSch jSch = new JSch();
//设置私钥路径
jSch.addIdentity("D:\\hehui\\jsch\\admin_private.ppk");
//传主机、端口、用户名获得一个会话
Session session = jSch.getSession("admin", "your host", 22);
//不进行严格模式检查
Properties config = new Properties();
config.put("StrictHostKeyChecking","no");
session.setConfig(config);
//连接会话
session.connect();
log.debug("是否连接:" + session.isConnected());
log.debug("会话:" + session);
//断开连接
session.disconnect();
log.debug("是否连接:" + session.isConnected());
}
/**
* 远程执行命令
* @throws JSchException
* @throws IOException
*/
@Test
public void test3() throws JSchException, IOException {
log.debug("会话:\r\n" + session);
ChannelExec channelExec = (ChannelExec)session.openChannel("exec");
channelExec.setCommand("df -h");
channelExec.connect();
InputStream inputStream = channelExec.getInputStream();
//命令执行结果
String result = IOUtils.toString(inputStream);
log.debug("执行结果:\r\n" + result);
}
/**
* 文件上传
*/
@Test
public void test4() {
try {
//使用ssh会话开启一个sftp文件传输的通道,Channel为抽象类
Channel channel = session.openChannel("sftp");
//强转为ChannelSftp
ChannelSftp channelSftp = (ChannelSftp) channel;
//连接该通道
channelSftp.connect();
String filePath = "D:\\hehui\\jsch\\apache-tomcat-9.0.35.tar.gz";
String fileName = "apache-tomcat-9.0.35.tar.gz";
//服务文件夹路径,只支持绝对路径
String serverDir = "/home/admin/jsch/";
AtomicReference<String> dir = new AtomicReference<>("/");
Stream.of(serverDir.split("\\/")).forEach(p -> {
try {
if (StringUtils.isNotEmpty(p)) {
String existDir = dir.get();
if (StringUtils.equals(existDir,"/")) {
dir.set(existDir + p);
} else {
dir.set(existDir + "/" + p);
}
channelSftp.cd(dir.get());
}
} catch (SftpException e1) {
log.debug("创建目录:" + p);
try {
channelSftp.mkdir(dir.get());
channelSftp.cd(dir.get());
} catch (SftpException e2) {
log.error("error:",e2);
throw new RuntimeException(e2);
}
}
});
FileInputStream in = new FileInputStream(filePath);
//上传
channelSftp.put(in,fileName);
//关闭传输通道
channelSftp.disconnect();
} catch (JSchException e) {
log.error("error",e);
} catch (FileNotFoundException e) {
log.error("error:",e);
} catch (SftpException e) {
log.error("error",e);
}
}
/**
* 文件下载
*/
@Test
public void test5(){
try {
//使用ssh会话开启一个sftp文件传输的通道,Channel为抽象类
Channel channel = session.openChannel("sftp");
//强转为ChannelSftp
ChannelSftp channelSftp = (ChannelSftp) channel;
//连接该通道
channelSftp.connect();
String serverDir = "/home/admin/jsch/";
String serverFile = "apache-tomcat-9.0.35.tar.gz";
FileOutputStream out = new FileOutputStream("D:\\hehui\\jsch\\apache-tomcat-9.0.35_download.tar.gz");
channelSftp.cd(serverDir);
channelSftp.get(serverFile,out);
//关闭通道
channelSftp.disconnect();
} catch (JSchException e) {
log.error("error:",e);
} catch (FileNotFoundException e) {
log.error("error:",e);
} catch (SftpException e) {
log.error("error:",e);
}
}
}