【问题标题】:Using JAVA intercepting Jsch prompt for entering password in UNIX shell使用 JAVA 拦截 Jsch 提示在 UNIX shell 中输入密码
【发布时间】:2016-02-21 07:33:47
【问题描述】:

我正在尝试使用 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:

在这之后什么都没有发生,我想让它在不提示输入密码的情况下运行。 有什么办法可以提供它执行成功的密码。

【问题讨论】:

    标签: java shell unix sudo su


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2019-02-26
      • 2016-02-20
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2021-06-04
      相关资源
      最近更新 更多