How to provide password for sudo command in java

Process p=Runtime.getRuntime().exec("sudo rm -rf /home/ftp");
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
bw.write("qwerty");
bw.flush();

I wrote this code, but it does not work

+4
source share
2 answers
String[] cmd = {"/bash/bin","-c"," echo password| sudo -S rm -rf /home/ftp"}; 
Process p = Runtime.getRuntime.exec(cmd); 

Provide input for the process using the pipe. Running echowith a space will remove it from the bash history.

You can also delete the story later:

new File(System.getProperty("user.home"), ".bash_history").delete();

but be careful with him. There is a trick to delete only the latest entries.

+1
source

Assign the necessary permissions to the user, and also close the buffer script by writing bw.close ();
If you continue to work in sudo mode, then the program can delete healthy files of important files that are required by other applications.

0
source

Source: https://habr.com/ru/post/1665504/


All Articles