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.connect();
out.write(password.getBytes());
out.flush();
out.write(newPassword.getBytes());
out.flush();
out.write(newPassword.getBytes());
out.flush();
channel.disconnect();
session.disconnect();
}
catch(Exception e) {
e.printStackTrace();
}
}
我第一次登录服务器时被要求更改密码。我正在尝试用JSch来做,但我不确定如何才能实现这一目标。据我所知,我无法使用任何命令,因为我在做任何事情之前都被迫更改密码,所以我无法使用
(echo old_password; echo new_password; echo new_password) | passwd username
答案 0 :(得分:1)
我通过调用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();
}
}
我在每个输入之前添加了睡眠以保持一致性,通常你想在输入每个密码之前等待输出,但对于我的用途,这样做。
答案 1 :(得分:0)
对我来说,可以在一个命令行中运行下一个命令,而不使用Thread.sleep
echo -e \"new-password\nnew-password\" | passwd user-linux