使用JAVA拦截Jsch提示在UNIX shell中输入密码

时间:2015-11-19 08:54:19

标签: java shell unix sudo su

我正在尝试使用java程序使用jsch运行shell命令。 命令需要sudo访问才能执行。以下是我的代码示例。

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

现在,当我运行它时,它停留在以下

Connected
[sudo] password for users:

在此之后没有任何反应我想让它在没有提示密码的情况下运行。 有什么方法可以提供密码以便执行以获得成功。

1 个答案:

答案 0 :(得分:3)

JSCH网站就此问题为您提供了example。我的想法是将密码写入OutputStream,代表ssh连接的“写”端。 相关代码块:

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