我使用了 VPN 服务,并使用 java 代码连接到它并在 Ubuntu 上运行它。每当 sudo openvpn 命令完全运行时,控制台就会卡住,并且不会在 while 循环后转到代码。但是如果我将 sudo 命令后面的代码包含在 while 循环内,它将运行之后的代码,但不运行 sudo 命令。我尝试添加“&”,以便该命令在后台运行,但没有用。请建议一种方法来执行此操作,因为我尝试了各种解决方案,但都是徒劳。下面是我编写的代码。
public class curl {
void sudo() throws IOException {
String command1 = "sudo openvpn --config /etc/openvpn/configFile ";
System.out.println(command1);
Process curlProc1;
curlProc1 = Runtime.getRuntime().exec(command1);
DataInputStream curlIn1 = new DataInputStream(
curlProc1.getInputStream());
String outputString1;
while ((outputString1 = curlIn1.readLine()) != null) {
System.out.println(outputString1);
}
String urly = "MyURL";
URL obj = new URL(urly);
HttpURLConnection con1 = (HttpURLConnection) obj.openConnection();
con1.setRequestMethod("GET");
con1.setDoOutput(true);
int responseCode = con1.getResponseCode();
System.out.println("Response Code : " + responseCode);
BufferedReader iny = new BufferedReader(
new InputStreamReader(con1.getInputStream()));
String output;
StringBuffer response = new StringBuffer();
while ((output = iny.readLine()) != null) {
response.append(output);
}
iny.close();
System.out.println(response.toString());
}
public static void main(String args[]) throws IOException, ClassNotFoundException, SQLException, JSONException{
curl brc= new curl();
brc.sudo();
}
}
最佳答案
您的问题是由 sudo 输出到错误流引起的。这正在发生:
curlProc1 = Runtime.getRuntime().exec(command1);
- 您的程序启动 sudo
- 由于 sudo 默认在终端上运行,因此它会向
stderr
输出“sudo:不存在 tty 且未指定 Askpass 程序”或“密码:”
while ((outputString1 = curlIn1.readLine()) != null) {
- 您的程序等待
stdout
上的输入 - 由于您从未读取过 stderr,因此 sudo 永远不会终止,因此 sudo 永远不会关闭 stdout,因此您的程序会卡住
解决此问题的一种快速方法是使用 process builder ,它有一个有用的选项,可以将 stderr
和 stdout
组合在一个流中,这意味着您只需要 1 个线程来读取流,并保持代码简单。
ProcessBuilder pb =
new ProcessBuilder("sudo", "openvpn", "--config", "/etc/openvpn/configFile");
pb.redirectErrorStream(true);
Process curlProc1 = pb.start();
....
由于 sudo 有可能会要求输入密码 ( you can configure it to ask for one instead of giving an error ),因此您可以在收到密码提示后通过写入进程的输入流来提供密码: p>
p.getOutputStream().write("correct battery horse staple\n".getBytes(STandardCharsets.UTF_8));
关于java - 在 Ubuntu 中连接到 VPN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51319688/