用java把服务器某个目录日志实时打印出来

1.引入第三方包

java 复制代码
<dependency>
    <groupId>com.jcraft</groupId>
    <artifactId>jsch</artifactId>
    <version>0.1.55</version>
</dependency>

2.代码如下

java 复制代码
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

public class MySQLPortForwarding {
    public static void main(String[] args) throws Exception{
        String sshHost = ""; //服务器ip
        String sshUsername = ""; //用户名称
        String sshPassword = ""; //用户密码
        String remoteHost = "localhost";
        int localPort = 3307; // 本地端口
        int remotePort = 3306; // 远程MySQL服务器端口

        JSch jsch = new JSch();
        Session session = jsch.getSession(sshUsername, sshHost, 22);
        session.setPassword(sshPassword);
        session.setConfig("StrictHostKeyChecking", "no");
        System.out.println("建立SSH连接...");
        session.connect();
       /*  //这步是做端口转发的,与文章无关,目的:服务器安装的有mysql,然后防火墙没开3306,本地无法直接连接mysql,
        // 这一步本地可以用过localhost:3307连接服务器的mysql
        int assignedPort = session.setPortForwardingL(localPort, remoteHost, remotePort);
        System.out.println("本地端口 " + assignedPort + " 被转发到 " + remoteHost + ":" + remotePort);*/
        String command = "tail -f " + "/tmp/debug.log";
        ChannelExec channel = (ChannelExec) session.openChannel("exec");
        channel.setCommand(command);

        InputStream in = channel.getInputStream();
        channel.connect();

        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line); // 实时打印日志内容
        }

        channel.disconnect();
        session.disconnect();
    }

}
相关推荐
朦胧之8 小时前
AI 编程-老项目改造篇
java·前端·后端
爱勇宝10 小时前
我做了一个只用来搜歌词的小 App
android·前端·后端
程序猿大帅12 小时前
别再只当调包侠了:用 Spring AI 落地 Function Calling,我被大模型硬生生砸出了三个大坑
java
程序员晓琪13 小时前
约定大于配置:基于 Java 包名自动生成 API 版本路由的最佳实践
java·spring boot·后端
Flittly13 小时前
【AgentScope Java新手村系列】(11)中断与恢复
java·spring boot·spring
众少成多积小致巨14 小时前
JNI (Java Native Interface) 技术手册中文参考指南
android·java·c++
东坡白菜14 小时前
破局全栈:前端开发的Java入门实战记录—JPA(2)
java·后端
Coffeeee20 小时前
如何使用Glide和Coil加载WebP动图
android·kotlin·glide
SimonKing20 小时前
艹,维护AI写的代码,我心态崩了......
java·后端·程序员
用户2986985301420 小时前
Java Word 文档样式进阶:段落与文本背景色设置完全指南
java·后端