4

I am trying to run shell command using jsch using java program. Command needs sudo access to get executed. Following is my code sample.

   String command1="sudo  restart oraserv";  
    java.util.Properties config = new java.util.Properties(); 
    config.put("StrictHostKeyChecking", "no");
    JSch jsch = new JSch();
    Session session;
    try {
        session = jsch.getSession(user, host, 22);
         session.setPassword(password);
            session.setConfig(config);
            session.connect();
            System.out.println("Connected");                
            Channel channel=session.openChannel("exec");                
            ((ChannelExec) channel).setCommand(command1);               
            channel.setInputStream(null);               
            ((ChannelExec)channel).setErrStream(System.err);                 
            InputStream in=channel.getInputStream();
            ((ChannelExec)channel).setPty(true);
            channel.connect();
            byte[] tmp=new byte[1024];
            while(true){
              while(in.available()>0){
                int i=in.read(tmp, 0, 1024);
                if(i<0)break;
                System.out.print(new String(tmp, 0, i));
              }
              if(channel.isClosed()){
                System.out.println("exit-status: "+channel.getExitStatus());
                break;
              }
              try{Thread.sleep(1000);}catch(Exception ee){}
            }
            channel.disconnect();
            session.disconnect();
            System.out.println("DONE");
    } catch (JSchException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Now when i run it it stuck at following

Connected
[sudo] password for users:

After this nothing happens i want to make it run without prompting for password. Is there any way i can supply it password for execution to get successful.

1 Answer 1

6

The JSCH website gives you an example on this very issue. The idea is to write the password to the OutputStream which represents the "write" end of the ssh connection. The relevant code block:

((ChannelExec)channel).setCommand("sudo -S -p '' "+command);


InputStream in=channel.getInputStream();
OutputStream out=channel.getOutputStream();
((ChannelExec)channel).setErrStream(System.err);

channel.connect();

out.write((sudo_pass+"\n").getBytes());
out.flush();
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.