Score:1

Run sudo commands in Java

cg flag

I am trying to run sudo commands in Java. I have trying to create a program in Java in order to execute nmap commands in it. I am using Java 20 and I am using ubuntu 22.04 as operating system. I am trying to run nmap in sudo mode because the output of the command is different based on which user exectued the command, this is the output when is runned in sudo mode:

Nmap scan report for 172.20.36.2
Host is up (0.026s latency).
MAC Address: 02:04:96:82:70:F6 (Unknown)
Nmap scan report for 172.20.36.3
Host is up (0.0021s latency).
MAC Address: 02:04:96:83:5B:56 (Unknown)
Nmap scan report for 172.20.36.10
Host is up (0.020s latency).
MAC Address: 00:1A:1E:00:6E:80 (Aruba, a Hewlett Packard Enterprise Company)

And this is the output when is runned in normal mode:

Nmap scan report for 172.20.36.10
Host is up (0.0016s latency).
Nmap scan report for 172.20.36.11
Host is up (0.0027s latency).
Nmap scan report for 172.20.36.12
Host is up (0.00079s latency).

My code is this:

        String[] cmd = {"/bin/bash","-c","nmap -sn "+network};
        Process process = runtime.exec(cmd);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        String[] lines = new String[3];
        int i = 0;
        while ((line = stdInput.readLine()) != null) {
          ....
        }

But when I am trying to run it in sudo mode like this is not executing at all:

        String[] cmd = {"/bin/bash","-c","sudo nmap -sn "+network};
        Process process = runtime.exec(cmd);

        BufferedReader stdInput = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = null;
        String[] lines = new String[3];
        int i = 0;
        while ((line = stdInput.readLine()) != null) {
          ....
        }

Do you have any suggestion what I should do?

muru avatar
us flag
Not executing _at all_? Then you should debug the java part of the code, which is a question for [so]
I sit in a Tesla and translated this thread with Ai:

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.