测试提供给“su”命令的密码是否与JSch库

时间:2016-04-15 02:52:18

标签: java session connect jsch channel

我正在尝试在su下的服务器上远程执行命令。具体来说,我正在远程执行:

su -c '[command]'

当我登录到远程服务器时,这是有效的。我连接会话并远程运行命令的代码如下所示:

我的问题很简单:如何检查out.write是否正在回复su命令中提供的密码提示?频道似乎已连接,只要不涉及su,该程序就会正常工作。

理想情况下,行动的顺序是:

  

远程命令已初始化 - >提示输入密码 - >远程输入密码[故障点] - >执行命令

必须是su。它不能是sudo

/**
 * Method to connect to session.  
 */
protected void connectSession(Session session){
    try {

        //connect to session and open exec channel
        session.connect();
        channel=session.openChannel("exec");

        ((ChannelExec)channel).setCommand(command); //set the command 
        ((ChannelExec)channel).setPty(true); //set PTY tru for Password input
        ((ChannelExec)channel).setErrStream(System.err);

        in = channel.getInputStream(); //set input stream
        out=channel.getOutputStream(); //set output stream and connect
        channel.connect();

        System.out.println("Channel was connected");
        out.write((sudo_pass+"\n").getBytes()); //write password upon prompt
        out.flush();

        //I believe the out.write and the out.flush section is not working. It probably breaks right before here. 

        System.out.println("Wrote sudo Pass");

    } catch (JSchException | IOException e) {
        System.out.println("Could not connect to session");
        e.printStackTrace();
    }
}
@Override
protected Integer RunCommand() throws Exception {
    int j = 0;
    System.out.println("Running command: " + command);  
    connectSession(session);

    byte[] tmp=new byte[1024];
    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()){
        if(in.available()>0) continue; 
        System.out.println("exit-status: "+channel.getExitStatus());
        break;
    }

    try{Thread.sleep(1000);}
    catch(Exception ee){}
    channel.disconnect();
}

我从中大量借用:

希望这有助于任何有类似问题的人!

1 个答案:

答案 0 :(得分:1)

如果输入错误的密码,su命令将中止并返回非零退出代码。

所以,你只需检查一下,&#34; exec&#34;输入密码后,频道会关闭。如果它关闭了,你就进入了#34;密码错误。

如果输入正确的密码,su启动shell并继续等待命令(或执行-c指定的命令)

请注意,su命令是专门设计的不是自动。试图自动化是错误的。

正确的方法包括:

  • 使用无密码sudo命令限制为您的特定任务的单个脚本
  • root用户的私钥限制为针对特定任务的单个脚本