UNIX passwd command exec in interactive mode

Anonymous
2009-12-02
2013-05-28

  • Anonymous
    2009-12-02

    Hi,

    I have a requirement of changing the UNIX password using passwd command. passwd command has got some prompts depending on the Operating system. Using Jsch i tried to establish connection and execute the command.

                JSch jsch = new JSch();
                Session session = jsch.getSession(username, hostname, 22);
                UserInfo ui = new MyUserInfo();
                session.setUserInfo(ui);
                session.connect(30000);
                Channel channel = session.openChannel("exec");
                ((ChannelExec) channel).setCommand("passwd " + username);
                ((ChannelExec) channel).setPty(true);
                channel.setInputStream(null);
                ((ChannelExec) channel).setErrStream(System.err);
                InputStream in = channel.getInputStream();
                channel.setInputStream(in);
                channel.setOutputStream(System.out);
                channel.connect();

    After giving the value to the first prompt, Enter existing login password: , it is prompting the next prompt. It appears ssh connection is handling the 2-way communication.
    Please help me out to resolve the issue. Quick response is highly appreciable.

    Thanks

     

  • Anonymous
    2009-12-02

    Sorry .. It appears ssh connection is *not* handling the 2-way communication

     
  • Brody S
    Brody S
    2011-02-20

    Vramanaj,

    I was able to accomplish this by the following code.

    String command = "(echo \""+password+"\"; echo \""+newPassword+"\"; echo \""+newPassword+"\") | passwd "+username;
            try {
                ChannelExec channel = (ChannelExec) session.openChannel("exec");
                channel.setPty(true);
                channel.setCommand(command);
    
                BufferedReader reader = new BufferedReader(new InputStreamReader(channel.getInputStream()));
                OutputStream writer = channel.getOutputStream();
    
                channel.connect();
    
                StringBuilder responseBuilder = new StringBuilder();
    
                while (!channel.isClosed() && !channel.isEOF()) {
                    String line = reader.readLine();
                    if (line != null) {
                        responseBuilder.append(line).append("\n");
                    }
                }
                System.out.println(responseBuilder.toString());
    
            } catch (Exception e) {
                e.printStackTrace();
            }