首页 > 解决方案 > 脚本外壳不返回所有输出消息

问题描述

我在下面有一个 shell 脚本,它执行 Sophos Antivirus 的验证调用:

#!/bin/bash
#Check state of antivirus sophos

echo "Vérification de l'état de l'antivirus"
state=`${1}bin/savdstatus 2>&1`
successtate="Sophos Anti-Virus is active"
echo "Return message : " $state
if [ "$state" = "$successtate" ]; then
    exit 0
else
    exit 1
fi

如果我从 shell 调用它,我可以看到输出是完整的:

在此处输入图像描述

我在 Java 类中使用它,

@Override
    public void checkAntivirusState() throws IOException {
        var processBuilder = new ProcessBuilder();
        // -- Linux -- Run a shell script
        processBuilder.command(pathToFileToExecute(), pathToSophosInstallationDir());
        var process = processBuilder.start();
        var output = new StringBuilder();
        try (var reader = new BufferedReader(new InputStreamReader(process.getInputStream()))) {

            String line;
            output.append("Antivirus or on-access scanning is disabled!").append(Chars.LF);
            while ((line = reader.readLine()) != null) {
                output.append(line).append(Chars.LF);
            }

            int exitVal = process.waitFor();
            if (exitVal == 0) {
                LOGGER.info("Antivirus Enabled");
            } else {
                var errorMessage = output.toString().replaceAll("[\r\n]", "");
                LOGGER.error(errorMessage);
                throw new SecurityException(errorMessage);
            }
            process.destroy();
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }

pathToFileToExecute() 和 pathToSophosInstallationDir() 分别返回下面脚本的路径和 shell 脚本使用的 Sophos 安装目录。

在执行时,状态不完整:只有“Sophos Anti-Virus 处于活动状态”被返回并捕获,而不是消息的按访问扫描部分。

我不明白为什么......你有什么想法吗?

编辑 1

Java 跟踪:

在此处输入图像描述

标签: javashell

解决方案


问题解决了,最终很简单:

当我直接启动 shell 时,我在 root 上,但应用程序正在使用另一个无权运行测试的用户。

所以我把我的用户添加到了sophosav组,就OK了。


推荐阅读