当前位置: 首页
科技数码
Spring Boot + sshd-sftp:SSH 命令与文件传输实践

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

热心网友 时间:2025-12-15
转载

在现代分布式系统中,服务器间的远程操作与文件传输是常见需求。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

游乐网为非赢利性网站,所展示的游戏/软件/文章内容均来自于互联网或第三方用户上传分享,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系youleyoucom@outlook.com。

同类文章
更多
4月规上工业原油产量1794万吨 同比增长1.2%

4月规上工业原油产量1794万吨 同比增长1.2%

国家统计局最新发布的能源数据显示,四月份我国原油生产与加工领域呈现出截然不同的发展态势。总体来看,上游生产保持稳健增长,而下游加工环节则面临一定压力。 从生产端来看,四月份规模以上工业原油产量达到1794万吨,同比增长1 2%,增速较三月份提升1 0个百分点。日均产量约为59 8万吨,生产节奏稳步加

时间:2026-05-18 18:08
iPhone 18 Pro手机壳曝光 相机模组尺寸或进一步增大

iPhone 18 Pro手机壳曝光 相机模组尺寸或进一步增大

知名爆料人分享了iPhone18Pro系列保护壳图片。设计延续前代风格,但相机模组尺寸可能进一步扩大,机身或略增厚,导致新保护壳与旧款不兼容。屏幕尺寸预计保持不变。综合信息显示,该系列更像是前代的强化升级版,重点在于内部性能与影像系统的提升。

时间:2026-05-18 18:08
百望股份与中关村两院战略合作共建产学研创投生态

百望股份与中关村两院战略合作共建产学研创投生态

百望股份与中关村学院、中关村人工智能研究院达成战略合作,共建产学研创投生态。依托百望的真实企业交易数据与两院的科研人才优势,在合规前提下挖掘数据要素价值。双方聚焦财税金融领域,利用AI技术研发智能应用,并通过共建数据沙箱、人才通道与共创机制,推动数据智能从学术创。

时间:2026-05-18 18:08
小米SU7 GT发布会5月21日举行 多款新品同步亮相

小米SU7 GT发布会5月21日举行 多款新品同步亮相

小米创始人雷军宣布,小米YU7GT将于5月21日晚7点发布。新车定位纯血GT,拥有修长车头、跑车宽体设计,最大马力1003匹,续航705公里。同场还将推出小米17Max手机、耳夹式耳机等多款生态新品。雷军解释,YU7GT侧重长途旅行与日常使用平衡,其纽北测试旨在验证极端条件下的整车性能。

时间:2026-05-18 18:08
英伟达洽谈领投印度AI初创公司Simplismart

英伟达洽谈领投印度AI初创公司Simplismart

英伟达正洽谈领投印度AI初创公司Simplismart,计划投资约2000万美元,投后估值预计达1亿美元。该公司专注于生成式AI和MLOps,若交易达成,其估值将在数月内从2500万美元跃升近四倍,增长迅猛。英伟达今年在AI领域投资已超400亿美元,持续扩张其生态布局。

时间:2026-05-18 18:08
热门专题
更多
刀塔传奇破解版无限钻石下载大全 刀塔传奇破解版无限钻石下载大全
洛克王国正式正版手游下载安装大全 洛克王国正式正版手游下载安装大全
思美人手游下载专区 思美人手游下载专区
好玩的阿拉德之怒游戏下载合集 好玩的阿拉德之怒游戏下载合集
不思议迷宫手游下载合集 不思议迷宫手游下载合集
百宝袋汉化组游戏最新合集 百宝袋汉化组游戏最新合集
jsk游戏合集30款游戏大全 jsk游戏合集30款游戏大全
宾果消消消原版下载大全 宾果消消消原版下载大全
  • 日榜
  • 周榜
  • 月榜
热门教程
更多
  • 游戏攻略
  • 安卓教程
  • 苹果教程
  • 电脑教程