使用 JAVA 更改 UNIX 密码

2022-01-23 00:00:00 command linux java jsch passwd

对不起,如果我的英语太糟糕了.我想问一下从 Java 执行passwd"命令(我使用 Netbeans IDE 和 JSCH 库)

sorry if my english is so bad. i wanna ask about executing "passwd" command from Java (i use Netbeans IDE & JSCH Library)

这是我的代码

String username = txtusername.getText();
    String password = txtpassword.getText();
    String ip = txtIP.getText();
    int port = 22;
    Session session = null;
    Session session2=null;
    ChannelExec channel = null;
    Channel channel2 = null;
    StringBuffer result = new StringBuffer();
    try
    {
        JSch shell = new JSch();
        session = shell.getSession(username, ip, port);
        java.util.Properties config = new java.util.Properties();
        config.put("StrictHostKeyChecking", "no");
        session.setConfig(config);
        session.setPassword(password);
        session.connect(3000);
        channel = (ChannelExec) session.openChannel("exec");
        ((ChannelExec)channel).setCommand("passwd");

        channel.setInputStream(null);
        channel.setOutputStream(null);
        ((ChannelExec)channel).setErrStream(System.err);

        InputStream in=channel.getInputStream();
        OutputStream out=channel.getOutputStream();

        PrintStream char_to_send_to_channel = new PrintStream(out,true);
        BufferedReader out_from_channel=new BufferedReader(new InputStreamReader(in));
        char_to_send_to_channel.println();

        String line;
        channel.connect();

        JOptionPane.showMessageDialog(null,"Channel opened!" +"
");

       // Process p = Runtime.getRuntime().exec("passwd");

        byte[] tmp=new byte[1024];
        while(true){
          while(in.available()>0){
            int i=in.read(tmp, 0, 1024);
            if(i<0) {
                  break;
              }
          }
        }
    } catch (IOException ex) {
        Logger.getLogger(connect.class.getName()).log(Level.SEVERE, null, ex);
    }  catch(JSchException | HeadlessException e){
        JOptionPane.showMessageDialog(null, e);
    }
}

问题是,我的输出就像

(current) UNIX password: 

如果我键入/输入当前的 UNIX 密码,什么也没有发生.我想更改 Ubuntu Server 帐户密码,它安装在我的 VMWare 上.我在我原来的操作系统上运行这个程序.简单地说,我希望我的输出是交互式的(输入和输出就像 linux 命令'passwd'的输出)

And if i type / input current UNIX password,nothing happened. I want change Ubuntu Server account password, its installed on my VMWare. And i run this program on my original OS. Simply, i want my output interactive (input and output just like output from linux command 'passwd')

我的代码有什么问题?:( 需要建议

Whats wrong with my code? :( Need Suggestions

推荐答案

passwd 默认会直接从 pty 而不是 stdin 读取.您需要将 --stdin 选项传递给 passwd.

passwd will by default read directly from the pty instead of stdin. You will need to pass the --stdin option to passwd.

有关详细信息,请参阅此问题的答案:在 shell 脚本中使用 passwd 命令.

For more information, see the answers to this question: Using the passwd command from within a shell script.

相关文章