Search code examples
javalinuxcentos

Calling journalctl from Java


When I run the following command as the root user in the Centos 7 Linux terminal, it produces 57 lines of output:

journalctl --output=json-pretty UNIT=firewalld.service  

So how do I change the code below to successfully call this from Java without having to leave my password in a file?

Here is my attempt. When I execute the following code, the console only outputs exit: 1:

String s;
Process p;
try {
    p = Runtime.getRuntime().exec("journalctl --output=json-pretty UNIT=firewalld.service");
    BufferedReader br = new BufferedReader(new InputStreamReader(p.getInputStream()));
    while ((s = br.readLine()) != null)
        System.out.println("line: " + s);
    p.waitFor();
    System.out.println ("exit: " + p.exitValue());
    p.destroy();
} catch (Exception e) {}  

Edit

When I add the following:

BufferedReader br2 = new BufferedReader(new InputStreamReader(p.getErrorStream()));
while ((s = br2.readLine()) != null)
    System.out.println("error line: " + s);

The following output gets generated:

error line: No journal files were found.
error line: Failed to get realtime timestamp: Cannot assign requested address

Is the problem related to permissions? When I run journalctl --output=json-pretty UNIT=firewalld.service as root from the Linux terminal, I get the 57 lines of output. But when I run journalctl --output=json-pretty UNIT=firewalld.service as a normal user, the terminal tells me that no files were found. I do not want to put my root password in Java code.

Is there some other way to call journalctl from Java without having to leave the system root password in a file?


Solution

  • Although the manual page for journalctl tells you that adding a user to systemd-journal should allow them to access all journals, that doesn't work on CentOS 7. I have initially worked around this by doing:

    chmod +s /usr/bin/journalctl
    

    But that gives everyone access to the journals and that might not be what you want.

    As @RealSkeptic pointed out the man page for systemd-journald.service indicates that additional access rights can be given to groups to read the journal (and states as well that adding a user to systemd-journal should be enough). Combining that information you can do

    sudo setfacl -Rnm g:systemd-journal:rx,d:g:systemd-journal:rx /run/log/journal/
    

    and after that adding the user to the systemd-journal group, as per the man pages, is enough to allow access to the journals:

    sudo usermod -a -G systemd-journal your_user_name