Change Unix Password with Java

How to create an API in Java to change the password of a Unix user?

Basically you'll need to work with 'passwd' unix command which is intended for changing the password.

You'll need to call this command from java by using the ProcessBuilder

or the older API Runtime

Now you'll also need to intercept the output of the passwd command if you want to run it interactively (like using some ui to enter the actual password and so on). In this case I would suggest you to read This article

You may consider also using some kind of predefined shell script that will allow to change the password non interactively. In this case you'll just invoke the script and it will do all the work.

Hope this helps

Java SSH change password on login

I solved my issue by calling channel.setPty(true);

private String user = "root",
newPassword = "test123";

private int port = 22;

public SSHConnection(String host, String password) {
try {
JSch jsch = new JSch();

Session session = jsch.getSession(user, host, port);
session.setPassword(password);
Properties config = new Properties();
config.put("StrictHostKeyChecking", "no");
session.setConfig(config);
session.connect();

ChannelExec channel = (ChannelExec)session.openChannel("exec");
OutputStream out = channel.getOutputStream();

((ChannelExec)channel).setErrStream(System.err);
channel.setPty(true);
channel.connect();

out.write((password + "\n").getBytes());
out.flush();
Thread.sleep(1000);

out.write((newPassword + "\n").getBytes());
out.flush();
Thread.sleep(1000);

out.write((newPassword + "\n").getBytes());
out.flush();
Thread.sleep(1000);

channel.disconnect();
session.disconnect();
}
catch(Exception e) {
e.printStackTrace();
}
}

I added sleeps before each input for consistency, normally you would want to wait for output before entering each password, but for my uses this will do.

Running UNIX commands as different user, from Java

Problem solved. Used JSch (http://www.jcraft.com/jsch/) to SSH into the server with known username and password, and execute command. Thanks all for your suggestions!



Related Topics



Leave a reply



Submit