如何提供sudo与root密码从Java? [英] How to supply sudo with root password from Java?

查看:118
本文介绍了如何提供sudo与root密码从Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想写一个小的Java应用程序,将覆盖我的 /etc/resolv.conf 文件(我在Ubuntu 12.04)。为此,我需要提供 root 密码:

  myUser @myMachine:〜$ sudo vim /etc/resolv.conf 
[sudo] myUser的密码:*****

这样做的过程有三个步骤:


  1. 输入 sudo vim / etc / resolv.conf

  2. 终端要求输入我的 root 密码

  3. 我输入密码,然后按 [Enter]

从我研究的一切,我可以使用以下执行上面的步骤#1:

  try {
String installTrickledCmd =sudo vim /etc/resolv.conf;
Runtime runtime = Runtime.getRuntime();
进程proc = runtime.exec(installTrickledCmd);
}
catch(Throwable throwable){
throw new RuntimeException(throwable);
}

但是当执行时,shell会提示我的Java进程密码。我不知道如何等待这个(上面的步骤#2),然后提供我的密码回到shell(上面的步骤3)。先感谢。

解决方案

您是否尝试过-S?

  $ echo mypassword | sudo -S vim /etc/resolv.conf 

来自man:



-S(stdin)选项使sudo从标准输入
而不是终端设备读取密码。密码后面必须是换行符
字符。


I'm trying to write a small Java app that will overwrite my /etc/resolv.conf file (I'm on Ubuntu 12.04). To do so, I need to supply my root password:

myUser@myMachine:~$ sudo vim /etc/resolv.conf 
[sudo] password for myUser: *****

So the process for doing this has three steps:

  1. Type sudo vim /etc/resolv.conf at terminal
  2. Terminal asks me to type my root password
  3. I enter the password and press [Enter]

From everything I've researched, I could use the following for performing step #1 above:

try {
    String installTrickledCmd = "sudo vim /etc/resolv.conf";
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec(installTrickledCmd);
}
catch(Throwable throwable) {
    throw new RuntimeException(throwable);
}

But when this executes, the shell will want to prompt my Java process for the password. I'm not sure how to wait for this (step #2 above) and then to supply my password back to the shell (step #3 above). Thanks in advance.

解决方案

Have you tried with -S ?

$echo mypassword | sudo -S vim /etc/resolv.conf

From man:

The -S (stdin) option causes sudo to read the password from the standard input 
instead of the terminal device.  The password must be followed by a newline 
character.

这篇关于如何提供sudo与root密码从Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆