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

I have written this code but it is not working

Azodious
  • 13,752
  • 1
  • 36
  • 71
Ankit Singh
  • 267
  • 2
  • 9
  • What error are you getting? What do you expect your program to do? in what way it is behaving different to you expectations? – Azodious Jan 02 '17 at 09:24
  • Maybe change the code to something less desastrous, an "ftp" user might have a bad day when getting this to run ... – fafl Jan 02 '17 at 09:33
  • 2
    Possible duplicate of [How to execute bash command with sudo privileges in Java?](http://stackoverflow.com/questions/18708087/how-to-execute-bash-command-with-sudo-privileges-in-java) – fafl Jan 02 '17 at 09:46
  • 1
    If you want the process that runs your Java code to be able to remove the entire `/home/ftp` directory structure, grant the user that access. Don't go to god mode for that. Especially, **never** hardcode user password in a program. Your program should not know the user password. Ever. – Andreas Jan 02 '17 at 09:55

2 Answers2

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

Provide the input for the process using the pipe. Starting the echo with space it will remove it from bash history.

You can also later delete the history:

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

but be careful with it. There is a trick to remove just last entries.

xenteros
  • 15,586
  • 12
  • 56
  • 91
  • 5
    Thats is **bad** advise: if you do it like this, everybody on the system that is allowed the "ps" command can **read** that password in plain text. You **never ever** put passwords directly into your command line. – GhostCat Jan 02 '17 at 09:26
  • 1
    Deleting .bash_history just makes a bad thing worse. If some random app deleted my history file, I'd be _very_ upset. – yshavit Jan 02 '17 at 09:40
0

Assign user the required permissions and also close the buffered writer by writing
bw.close();
If you keep going for sudo mode then program may delete some important files that are required by other applications to work in a healthy way.

Himanshu
  • 11
  • 1