通过JSch远程调度linux

引用最新的依赖(官方的已经很久没更新了,这个是开源的)

复制代码
<dependency>
    <groupId>com.github.mwiede</groupId>
    <artifactId>jsch</artifactId>
    <version>2.27.2</version>
</dependency>

参考:解决com.jcraft.jsch.JSchException: Algorithm negotiation fail-CSDN博客

java 复制代码
import com.jcraft.jsch.*;

import java.io.InputStream;

public class SSHConnection {
    public static void main(String[] args) {
        JSch jsch = new JSch();
        Session session = null;

        try {
            // 1. 创建会话并连接
            session = jsch.getSession("账号名", "ip地址", 22);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword("密码");
            session.connect();
            System.out.println("SSH连接成功");

            // 2. 创建执行通道
            ChannelExec channelExec = (ChannelExec) session.openChannel("exec");

            // 3. 设置命令 - 这里测试环境变量是否加载
            String command = "source /etc/profile; source ~/.bashrc; echo $PATH; ls -lh";
            channelExec.setCommand(command);

            // 4. 设置输入输出流
            channelExec.setInputStream(null);
            channelExec.setErrStream(System.err);

            // 5. 获取输出流
            InputStream in = channelExec.getInputStream();

            // 6. 连接并执行命令
            channelExec.connect();
            System.out.println("执行命令: " + command);

            // 7. 读取命令输出
            byte[] tmp = new byte[1024];
            while (true) {
                while (in.available() > 0) {
                    int i = in.read(tmp, 0, 1024);
                    if (i < 0) break;
                    System.out.print(new String(tmp, 0, i));
                }
                if (channelExec.isClosed()) {
                    System.out.println("\n退出状态: " + channelExec.getExitStatus());
                    break;
                }
                Thread.sleep(100);
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 8. 关闭连接
            if (session != null && session.isConnected()) {
                session.disconnect();
                System.out.println("SSH连接已关闭");
            }
        }
    }
}

运行结果

可根据上面代码进一步优化。

相关推荐
chlk12311 小时前
Linux文件权限完全图解:读懂 ls -l 和 chmod 755 背后的秘密
linux·操作系统
舒一笑11 小时前
Ubuntu系统安装CodeX出现问题
linux·后端
改一下配置文件12 小时前
Ubuntu24.04安装NVIDIA驱动完整指南(含Secure Boot解决方案)
linux
碳基沙盒12 小时前
OpenClaw 多 Agent 配置实战指南
运维
深紫色的三北六号21 小时前
Linux 服务器磁盘扩容与目录迁移:rsync + bind mount 实现服务无感迁移(无需修改配置)
linux·扩容·服务迁移
SudosuBash1 天前
[CS:APP 3e] 关于对 第 12 章 读/写者的一点思考和题解 (作业 12.19,12.20,12.21)
linux·并发·操作系统(os)
哈基咪怎么可能是AI1 天前
为什么我就想要「线性历史 + Signed Commits」GitHub 却把我当猴耍 🤬🎙️
linux·github
十日十行2 天前
Linux和window共享文件夹
linux
Sinclair2 天前
简单几步,安卓手机秒变服务器,安装 CMS 程序
android·服务器
木心月转码ing2 天前
WSL+Cpp开发环境配置
linux