gpt4 book ai didi

Java SSH 登录时更改密码

转载 作者:行者123 更新时间:2023-12-01 10:33:04 29 4
gpt4 key购买 nike

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

最佳答案

我通过调用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();
}
}

为了保持一致性,我在每次输入之前添加了 sleep ,通常您会希望在输入每个密码之前等待输出,但对于我的使用来说,这样做就可以了。

关于Java SSH 登录时更改密码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34978951/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com