0

I am looking for a way to fire passwd onto a remote unix server via a java code. I am using Jsch, I can successfully execute commands like find, zip, get. But when I pass 'passwd' command nothing happens. The motive is to create an application which can change the password of unix server in every 10 days.

This is the code I am trying to use (find command works fine)

JSch sftp=new JSch();
        Session session=sftp.getSession("Test", "150.236.9.75");
        session.setConfig("StrictHostKeyChecking", "no");
        session.setConfig("compression.s2c", "zlib@openssh.com,zlib,none");
        session.setConfig("compression.c2s", "zlib@openssh.com,zlib,none");
        session.setConfig("compression_level", "9");
        session.setPassword("Test@123");
        session.connect();

        if(session.isConnected())
        {
            String line="";
            System.out.println("connected");
            ChannelExec ch=(ChannelExec) session.openChannel("exec");
            String Command="passwd -s; Test@123; Pass@123; Pass@123";
            //String Command="find *";
            InputStream in = ch.getInputStream();
            ch.setCommand(Command);
            ch.connect();
            byte[] buffer = new byte[1024]; 
            int bytes;
            do {
                while (in.available() > 0) {
                    bytes = in.read(buffer, 0, 1024);
                    String file=new String(buffer, 0, bytes);
                    System.out.println(file);
                    line=line+file;
                }
            } while (!ch.isClosed());   
            ch.disconnect();
        }
        session.disconnect();
Vaibhav Arora
  • 91
  • 1
  • 7
  • If I had to guess, the problem is that `passwd` asks for input after your run it and your program might not handle that correctly. Please post some relevant pieces of code so that we can see what you are doing right now. Are you able to interact with other commands that ask for user input or only those that send to STDOUT? – zero298 Jan 21 '15 at 20:00
  • Get rid of the `available()` and `while (!ch.isClosed())` tests. Neither of them does what you seem to think. The loop should be `while ((bytes = in.read(buffer)) > 0) ...` – user207421 Jan 21 '15 at 20:20

2 Answers2

2

The passwd command requires interative input (i.e. read from stdin), see How to write in Java to stdin of ssh?

Community
  • 1
  • 1
Alex
  • 2,435
  • 17
  • 18
0

For me running the next command without using Thread.sleep works:

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