游乐游手机版
首页/科技数码/文章详情

Spring Boot + sshd-sftp:SSH 命令与文件传输实践

时间:2025-12-15 21:35
在现代分布式系统中,服务器间的远程操作与文件传输是常见需求。SSH作为一种安全的网络协议,为远程登录和文件传输提供了可靠保障。 前言在现代分布式系统中,服务器间的远程操作与文件传输是常见需求。SSH

在现代分布式系统中,服务器间的远程操作与文件传输是常见需求。SSH作为一种安全的网络协议,为远程登录和文件传输提供了可靠保障。

前言

在现代分布式系统中,服务器间的远程操作与文件传输是常见需求。SSH作为一种安全的网络协议,为远程登录和文件传输提供了可靠保障。

环境准备

sshd-sftp是Apache MINA项目旗下的SSH服务器组件,支持SSHv2协议,提供了丰富的API用于构建SSH客户端和服务器。相比传统的JSch库,sshd-sftp具有更活跃的社区维护和更完善的功能支持,尤其在处理大文件传输和并发连接时表现更优。

案例

效果图

图片图片

核心依赖

org.apache.sshd sshd-sftp 2.10.0

SSH 连接管理

建立和管理SSH连接是所有操作的基础,合理的连接池设计能有效提升系统性能。

创建SshClientUtil工具类管理连接生命周期:

import lombok.extern.slf4j.Slf4j;import org.apache.sshd.client.SshClient;import org.apache.sshd.client.session.ClientSession;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Component;import java.io.IOException;@Slf4j@Componentpublic class SshClientUtil { @Value("${ssh.host:182.168.1.101}") private String host; @Value("${ssh.port:22}") private int port; @Value("${ssh.username:root}") private String username; @Value("${ssh.password:root}") private String password; @Value("${ssh.timeout:5000}") private int timeout; private SshClient client; private ClientSession session; /** * 建立SSH连接 */ public void connect() throws IOException { if (session != null && session.isOpen()) { return; } client = SshClient.setUpDefaultClient(); client.start(); session = client.connect(username, host, port) .verify(timeout) .getSession(); session.addPasswordIdentity(password); session.auth().verify(timeout); log.info("SSH连接成功"); } /** * 断开SSH连接 */ public void disconnect() throws IOException { if (session != null && session.isOpen()) { session.close(); } if (client != null && client.isStarted()) { client.stop(); } } public ClientSession getSession() throws IOException { if (session == null || session.isEmpty() ||session.isClosed()) { connect(); } return session; }}

远程命令执行

通过SSH协议执行远程命令是服务器管理的常用功能,需要处理命令输出和错误信息。

import org.apache.sshd.client.channel.ChannelExec;import org.apache.sshd.client.channel.ClientChannelEvent;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import java.io.*;import java.util.ArrayList;import java.util.Arrays;import java.util.List;@Servicepublic class RemoteCommandService { @Autowired private SshClientUtil sshClientUtil; @Value("${ssh.charset:UTF-8}") private String charset; /** * 执行单条SSH命令 * * @param command 命令字符串 * @return 命令输出结果 */ public String executeCommand(String command) throws IOException { try (ChannelExec channel = sshClientUtil.getSession().createExecChannel(command)) { ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); ByteArrayOutputStream errorStream = new ByteArrayOutputStream(); channel.setOut(outputStream); channel.setErr(errorStream); channel.open(); channel.waitFor(Arrays.asList(ClientChannelEvent.CLOSED), 0); int exitStatus = channel.getExitStatus(); if (exitStatus != 0) { String errorMsg = new String(errorStream.toByteArray(), charset); throw new RuntimeException("命令执行失败: " + errorMsg); } return new String(outputStream.toByteArray(), charset); } } /** * 执行多条命令(按顺序执行) * * @param commands 命令列表 * @return 命令输出结果列表 */ public List executeCommands(List commands) throws IOException { List results = new ArrayList<>(); for (String cmd : commands) { results.add(executeCommand(cmd)); } return results; }}

文件上传与下载

SFTP是基于SSH的安全文件传输协议,相比FTP具有更高的安全性。

import org.apache.sshd.sftp.client.SftpClient;import org.apache.sshd.sftp.client.SftpClientFactory;import org.apache.sshd.sftp.common.SftpException;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.stereotype.Service;import java.io.*;import java.nio.file.Files;import java.nio.file.Path;import java.nio.file.Paths;import java.util.ArrayList;import java.util.Arrays;import java.util.List;@Servicepublic class SftpFileService { @Autowired private SshClientUtil sshClientUtil; @Value("${ssh.charset:UTF-8}") private String charset; /** * 上传本地文件到远程服务器 * * @param localFilePath 本地文件路径 * @param remoteDir 远程目录路径 */ public void uploadFile(String localFilePath, String remoteDir) throws IOException { try (SftpClient client = SftpClientFactory.instance().createSftpClient(sshClientUtil.getSession()); SftpClient.CloseableHandle handle = client.open(remoteDir, SftpClient.OpenMode.Write, SftpClient.OpenMode.Create)) { // 上传文件 Path local = Paths.get(localFilePath); client.write(handle, 0, Files.readAllBytes(local)); } } /** * 从远程服务器下载文件 * * @param remoteFilePath 远程文件路径 * @param localDir 本地目录路径 */ public void downloadFile(String remoteFilePath, String localDir) throws IOException { try (SftpClient client = SftpClientFactory.instance().createSftpClient(sshClientUtil.getSession()); SftpClient.CloseableHandle handle = client.open(remoteFilePath, SftpClient.OpenMode.Read); OutputStream out = Files.newOutputStream(Paths.get(localDir))) { long size = client.stat(handle).getSize(); byte[] buffer = new byte[8192]; for (long offset = 0; offset < size; ) { int len = client.read(handle, offset, buffer, 0, buffer.length); out.write(buffer, 0, len); offset += len; } } } /** * 递归创建远程目录 */ private void mkdirs(SftpClient client, String dir) throws IOException { String[] dirs = dir.split("/"); String currentDir = ""; for (String d : dirs) { if (d.isEmpty()) continue; currentDir += "/" + d; try { client.stat(currentDir); // 检查目录是否存在 } catch (IOException e) { client.mkdir(currentDir); // 不存在则创建 } } }}

来源:https://www.51cto.com/article/824502.html
上一篇四海兄弟:故乡PS5销量领先,总销120万份反映平台差异 下一篇二手车选购七大要点:避坑指南
本站内容用于信息整理与展示,如有侵权或内容问题请及时联系处理。

相关推荐

补充同频道和同主题内容,方便继续浏览更多相关内容。

同类最新

继续查看同栏目最近更新的文章。

更多
2026中国航空产业大会10月底南昌启幕:首次与航博会同期举办,聚焦低空经济新路径
科技数码 · 2026-08-31

2026中国航空产业大会10月底南昌启幕:首次与航博会同期举办,聚焦低空经济新路径

2026中国航空产业大会与南昌航空产业博览会将于10月31日至11月4日在南昌国际博览城首次同期举办。大会聚焦低空经济,设置主旨报告、行业专家报告及低空产业洽谈会等主题活动,旨在探讨航空产业新路径,推动低空物流、城市巡检等新业态集聚,打造中部领先、全国知名的航空产业交流高地。

联想来酷Air 16酷睿5 315版开售:国补后3739元,16英寸轻薄本选购指南
科技数码 · 2026-08-28

联想来酷Air 16酷睿5 315版开售:国补后3739元,16英寸轻薄本选购指南

联想来酷Air 16酷睿5 315版于8月27日正式开售,搭载6核处理器与12GB内存,配备16英寸16:10屏幕。叠加国家补贴后预估到手价仅3739 15元,主打长续航与静音办公。本文详细解析其硬件配置、接口布局及购买建议,助您快速决策。

牛来AirPods保护套海外走红:萌趣硅胶设计引发关注
科技数码 · 2026-08-28

牛来AirPods保护套海外走红:萌趣硅胶设计引发关注

一款名为“牛来”的AirPods硅胶保护套在日本市场引发关注,售价约1726日元。其独特的搞怪萌趣造型、兼容多代机型的硅胶材质以及专属挂饰设计,使其在社交平台上迅速走红,成为近期备受瞩目的国产原创数码周边产品。

行李箱选购全攻略:材质、轮子与尺寸避坑指南
科技数码 · 2026-08-28

行李箱选购全攻略:材质、轮子与尺寸避坑指南

选购行李箱时,材质、轮子和尺寸是核心决策点。PP材质抗冲击且轻便,适合频繁托运;万向轮决定推行顺滑度;尺寸需匹配航空限重。本文拆解关键参数,结合具体产品案例,助您选出耐用且实用的行李箱。

《湮灭之潮》成都试玩会:技嘉RTX 5080风魔显卡实测体验
科技数码 · 2026-08-28

《湮灭之潮》成都试玩会:技嘉RTX 5080风魔显卡实测体验

2026年8月《湮灭之潮》成都试玩会圆满举行,千名玩家现场体验西方奇幻大作。文章重点解析技嘉RTX 5080风魔显卡在虚幻5引擎下的表现,涵盖Blackwell架构、DLSS 4 5技术及16GB GDDR7显存对高画质流畅运行的支撑作用。