Reputation: 971
I am trying to change user password in linux from java program by sending password in outputstream but it is not done.
My java program is like
Process process = Runtime.getRuntime().exec("sudo passwd sampleuser");
OutputStream outputStream = process.getOutputStream();
InputStream inputStream = process.getInputStream();
PrintWriter printWriter=new PrintWriter(outputStream);
printWriter.write("123456");
printWriter.write("\n");
printWriter.flush();
My program fails here and it ask for password but I does not want this case.
Is there any possibility for providing password from java program ? can you suggest me,how I will do it successfully or is there any shell api's available for it.
Same thing is done successful when I try using shell script and calling it from my java program as
Process process = Runtime.getRuntime().exec("bash first.sh");
My shell script is
i="123456"
echo -e $i"\n"$i|sudo -S passwd sampleuser
It changes user password successfully.
Upvotes: 3
Views: 3821
Reputation: 1
If someone is looking for an answer, I just find a way with this lines :
try {
Process p = Runtime.getRuntime().exec(new String[] {"sudo", "/bin/sh", "-c", "echo \"user:newpassword\" | sudo chpasswd"} );
p.waitFor();
} catch (IOException | InterruptedException e1) {
e1.printStackTrace();
}
Upvotes: 0
Reputation: 4732
I'm not sure why your approach fails. I suppose passwd uses a different stream.
But use ExpectJ for this. It is made just for such cases.
Upvotes: 0
Reputation: 15052
It will ask for password. Look at your shell script. You execute a command that asks for super user privileges(sudo
). Your program will prompt for a password unless you run it as a super user.
To break down your shell script:
i="123456"
echo -e $i"\n"$i|sudo -S passwd sampleuser
sudo -S
means :
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.
And that is what your script is doing, it is setting password(passwd
) for your sampleuser
as i
. And since you are using -S
it is reading from the standard input,to which you have already given your variable i
. And you are doing all this as a super user! keep that in mind.
Now look back at your java program and try for the changes accordingly. Do you have super user privileges when you run your program? No,you don't.
Upvotes: 5