我正在尝试在 Java 中运行 sudo 命令。我尝试用 Java 创建一个程序以便在其中执行 nmap 命令。我使用的是 Java 20,操作系统是 ubuntu 22.04。我尝试在 sudo 模式下运行 nmap,因为命令的输出根据执行命令的用户而不同,这是在 sudo 模式下运行时的输出:
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)
这是在正常模式下运行时的输出:
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).
我的代码是这样的:
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) {
....
}
但是当我尝试以 sudo 模式运行它时,它根本没有执行:
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) {
....
}
你对我该怎么做有什么建议吗?