簡體   English   中英

Java SSH登錄時更改密碼

[英]Java SSH change password on login

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();
    }
}

為了保持一致性,我在每次輸入之前添加了sleeps,通常您希望在輸入每個密碼之前先等待輸出,但是對於我來說,這樣做是可以的。

對我來說,可以在一個命令行中運行下一個命令,而無需使用Thread.sleep

echo -e \"new-password\nnew-password\" | passwd user-linux

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM