用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();
    }

}
相关推荐
张紫娃2 分钟前
Spring @Scope, @Lazy, @DependsOn, @Required, @Lookup
java·后端·spring
简诚3 分钟前
java实现RabbitMQ消息发送和接收功能(包含测试)
java·rabbitmq·java-rabbitmq
結城1 小时前
Spring Security如何拿到登录用户的信息
java·spring·mybatis
GalaxyPokemon2 小时前
LeetCode - 2. 两数相加
java·前端·javascript·算法·leetcode·职场和发展
运维行者_3 小时前
Azure数据库监控:如何在2025年选择合适的工具
运维·服务器·网络·数据库·flask·自动化·azure
dualven_in_csdn5 小时前
搞了两天的win7批处理脚本问题
java·linux·前端
小镇学者6 小时前
【PHP】导入excel 报错Trying to access array offset on value of type int
android·php·excel
C++chaofan7 小时前
74. 搜索二维矩阵
java·算法·leetcode·矩阵
玩转4G物联网7 小时前
零基础玩转物联网-串口转以太网模块如何快速实现与MQTT服务器通信
服务器·物联网·网络协议·tcp/ip·信息与通信·iot·fs100p
爬呀爬的水滴7 小时前
解决Ubuntu24.04版本,右键没有共享选项的问题
linux·服务器·ubuntu·samba·共享文件夹