我使用过VPN服务,并使用Java代码连接到该服务并在Ubuntu上运行它。每当sudo openvpn命令完全运行时,控制台就会卡住,而while循环后不会进入该代码。在while循环内将sudo命令后的代码包括在内,它将在此之后运行代码,但随后不运行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();
}
}
答案 0 :(得分:1)
您的问题是由sudo输出到错误流的事实引起的。这正在发生:
curlProc1 = Runtime.getRuntime().exec(command1);
stderr
输出“ sudo:不存在tty且未指定askpass程序”或“ Password:” while ((outputString1 = curlIn1.readLine()) != null) {
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.getOutputStream().write("correct battery horse staple\n".getBytes(STandardCharsets.UTF_8));