SpringBoot集成JSch快速入门demo

互联架构唠唠嗑 2024-03-27 06:16:58
1.JSch介绍JSch是SSH2的纯Java实现。 JSch允许您连接到sshd服务器并使用端口转发,X11转发,文件传输等,并且可以将其功能集成到您自己的Java程序中。 2.实现原理根据远程主机的IP地址,用户名和端口,建立会话(Session)设置用户信息(包括密码和Userinfo),然后连接session,getSession()只是创建一个session,需要设置必要的认证信息之后,调用connect()才能建立连接。设置channel上需要远程执行的Shell脚本,连接channel,就可以远程执行该Shell脚本,调用openChannel(String type) 可以在session上打开指定类型的channel。该channel只是被初始化,使用前需要先调用connect()进行连接。可以读取远程执行Shell脚本的输出,然后依次断开channel和session的连接3.代码工程实验目标:实现文件上传到服务,服务器下载文件以及执行服务器命令 pom.xml springboot-demo com.et 1.0-SNAPSHOT 4.0.0 JSch 8 8 org.springframework.boot spring-boot-starter-web org.springframework.boot spring-boot-autoconfigure org.springframework.boot spring-boot-starter-test test com.jcraft jsch 0.1.55 org.projectlombok lombok com.alibaba fastjson 1.2.78 remote.javapackage com.et.jsch.model;import lombok.Data;@Datapublic Remote { private String host; private final int port = 22; private String user; private String password; private final String identity = "~/.ssh/id_rsa"; private String passphrase;} JSchUtil.javapackage com.et.jsch.util;import com.et.jsch.model.Remote;import com.jcraft.jsch.*;import lombok.extern.slf4j.Slf4j;import java.io.*;import java.nio.file.Files;import java.nio.file.Paths;import java.util.ArrayList;import java.util.List;import java.util.function.Function;/** * ssh tools */@Slf4jpublic JSchUtil { public static final int SESSION_TIMEOUT = 30000; public static final int CONNECT_TIMEOUT = 3000; /** * get session * * @param remote ssh server info * @return session * @throws JSchException / */ public static Session getSession(Remote remote) throws JSchException { JSch jSch = new JSch(); if (Files.exists(Paths.get(remote.getIdentity()))) { jSch.addIdentity(remote.getIdentity(), remote.getPassphrase()); } Session session = jSch.getSession(remote.getUser(), remote.getHost(), remote.getPort()); session.setPassword(remote.getPassword()); session.setConfig("StrictHostKeyChecking", "no"); return session; } /** * excute remote command * * @param session session * @param command command * @return / * @throws JSchException / */ public static List remoteExecute(Session session, String command) throws JSchException { log.debug(">> {}", command); List resultLines = new ArrayList<>(); ChannelExec channel = null; try { channel = openExecChannel(session); channel.setCommand(command); InputStream input = channel.getInputStream(); channel.connect(CONNECT_TIMEOUT); try { BufferedReader inputReader = new BufferedReader(new InputStreamReader(input)); String inputLine; while ((inputLine = inputReader.readLine()) != null) { log.debug(" {}", inputLine); resultLines.add(inputLine); } } finally { if (input != null) { try { input.close(); } catch (Exception e) { log.error("JSch inputStream close error:", e); } } } } catch (IOException e) { log.error("IOException:", e); } finally { disconnect(channel); } return resultLines; } /** * scp file to remote server * * @param session session * @param source local file * @param destination remote target file * @return file size */ public static long scpTo(Session session, String source, String destination) { FileInputStream fileInputStream = null; ChannelExec channel = null; try { channel = openExecChannel(session); OutputStream out = channel.getOutputStream(); InputStream in = channel.getInputStream(); boolean ptimestamp = false; String command = "scp"; if (ptimestamp) { command += " -p"; } command += " -t " + destination; channel.setCommand(command); channel.connect(CONNECT_TIMEOUT); if (checkAck(in) != 0) { return -1; } File _lfile = new File(source); if (ptimestamp) { command = "T " + (_lfile.lastModified() / 1000) + " 0"; // The access time should be sent here, // but it is not accessible with JavaAPI ;-< command += (" " + (_lfile.lastModified() / 1000) + " 0\n"); out.write(command.getBytes()); out.flush(); if (checkAck(in) != 0) { return -1; } } //send "C0644 filesize filename", where filename should not include '/' long fileSize = _lfile.length(); command = "C0644 " + fileSize + " "; if (source.lastIndexOf('/') > 0) { command += source.substring(source.lastIndexOf('/') + 1); } else { command += source; } command += "\n"; out.write(command.getBytes()); out.flush(); if (checkAck(in) != 0) { return -1; } //send content of file fileInputStream = new FileInputStream(source); byte[] buf = new byte[1024]; long sum = 0; while (true) { int len = fileInputStream.read(buf, 0, buf.length); if (len <= 0) { break; } out.write(buf, 0, len); sum +="len;" send '\0' buf[0]="0;" 1); out.flush(); if (checkack(in) !="0)" return -1; sum; catch (jschexception e) log.error("scp to caught jsch exception, ", e); (ioexception io (exception error, finally closeinputstream(fileinputstream); disconnect(channel); ** * scp remote file local @param session source destination @return size public static long scpfrom(session session, string source, destination) fileoutputstream channelexec channel="null;" try channel.setcommand("scp -f " source); outputstream out="channel.getOutputStream();" inputstream in="channel.getInputStream();" channel.connect(); byte[] buf="new" byte[1024]; while (true) ) read '644 ' in.read(buf, 4); filesize="0;" (in.read(buf, 1) < (buf[0]="=" ') 10l (long) - '0'); for (int i="0;" ; i++) i, (buf[i]="=" (byte) 0x0a) string(buf, i); a content of lfile (files.isdirectory(paths.get(destination))) fileoutputstream(destination file.separator file); else fileoutputstream(destination); int len="in.read(buf," buf.length); (len>= fileSize) { fileOutputStream.write(buf, 0, (int) fileSize); break; } fileOutputStream.write(buf, 0, len); fileSize -= len; } return sum; } catch (JSchException e) { log.error("scp to caught jsch exception, ", e); } catch (IOException e) { log.error("scp to caught io exception, ", e); } catch (Exception e) { log.error("scp to error, ", e); } finally { closeOutputStream(fileOutputStream); disconnect(channel); } return -1; } /** * remote edit * * @param session session * @param source target file * @param process edit command collect * @return isSuccess */ private static boolean remoteEdit(Session session, String source, Function
0 阅读:170

互联架构唠唠嗑

简介:感谢大家的关注