Jsch 运行 带有组合 tail 命令的远程 jar 无法正常工作

Jsch running a remote jar with combined tail command is not working properly

我正在尝试使用 JSch 通过 SSH 运行 远程 linux 服务器(在不同端口上)上的一些独立 spring 引导 jar。我在命令中使用 tail,因为我需要 tomcat 服务器日志。当我启动 运行s 独立 jar 的服务时,有些 jar 不是 运行ning。

这是我用于 运行 独立 jar 的示例脚本:

nohup java -jar foo.jar --server.port=10000 > log.txt 2> errors.txt & tail -f log.txt

这是我的代码:

StringBuilder sb = new StringBuilder();
Session session = null;
ChannelExec channel = null;
InputStreamReader isr = null;
BufferedReader br = null;
try {
    String command1 = "nohup java -jar " + jarFileDir + "/" + jarFileName + " --server.port=" + port
            + " > " + jarFileDir + "/log.txt 2> " + jarFileDir + "/errors.txt & tail -f " + jarFileDir + "/log.txt";

    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    JSch jsch = new JSch();
    session = jsch.getSession(username, ip, port);
    session.setPassword(password);
    session.setConfig(config);
    session.connect();

    channel = (ChannelExec)session.openChannel("exec");
    channel.setPty(true);
    isr = new InputStreamReader(channel.getInputStream());
    br = new BufferedReader(isr);
    channel.setCommand(command1);
    channel.connect();

    String msg;
    while ((msg = br.readLine()) != null) {
        //jar logs is being readed and processed here
    }

} catch (Exception e) {
    //handle exception
} finally {
    //close all the connections
    if (br != null) br.close();
    if (isr != null) isr.close();
    if (channel != null) channel.disconnect();
    if (session != null) session.disconnect();
}

关于问题的日志在这里:

tail: 无法打开 'log.txt' 进行读取: 没有那个文件或目录 尾巴:没有文件剩余

nohup java -jar foo.jar --server.port=10000 > log.txt 2> errors.txt & tail -f log.txt

您在此处 运行 两个单独的命令:

nohup java -jar foo.jar --server.port=10000 > log.txt 2> errors.txt
tail -f log.txt

这有一个竞争条件。在第一个命令有机会创建文件之前,第二个命令可以启动并尝试打开 log.txt

解决方法是确保在启动 tail 命令之前创建 log.txt。你可以这样做:

touch log.txt
nohup java -jar foo.jar --server.port=10000 > log.txt 2> errors.txt &
tail -f log.txt

或一行:

touch log.txt; nohup java etc... & tail -f log.txt

Mention the command as mentioned below and i have added end of the command as > /dev/null 2>&1 & to run the background process using jsch

String command1 = "nohup java -jar " + jarFileDir + "/" + jarFileName + " --server.port=" + port + " > " + jarFileDir + "/log.txt 2> " + jarFileDir + "/errors.txt & tail -f " + jarFileDir + "/log.txt > /dev/null 2>&1 &";