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?