java - 测试提供给 "su"命令的密码是否成功使用 JSch 库

标签 java session connect jsch channel

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

su -c '[command]'

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

我的问题希望非常简单:如何检查 out.write 是否在回复 su 命令中提供的密码提示? channel 似乎已连接,只要不涉及 su,程序似乎就可以运行。

理想的操作顺序是:

remote command initialized -> prompt for password -> input password remotely [failure point] -> execute command

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

我大量借鉴了:

希望这对遇到类似问题的人有帮助!

最佳答案

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

因此,您只需检查“exec” channel 是否在您输入密码后关闭。如果它确实关闭,则说明您“输入”了错误的密码。

如果你输入了正确的密码,su会启动一个shell并一直等待命令(或者执行-c指定的命令)


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

正确的做法包括:

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

关于java - 测试提供给 "su"命令的密码是否成功使用 JSch 库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36637467/

相关文章:

php - 如何使每个 php 脚本实例的 session 变量唯一?

security - 安全地实现 session 状态和 'keep me logged in'功能

javascript - node.js connect-auth 应用程序?示例(用户注册/用户/ session 管理)

javascript - firebase.database() 不是函数 - 新的 Firebase 项目

java - Eclipse + Maven -> eclipse.ini

java - QuickFIX/J - 故障转移策略

java - 需要澄清并行处理

java - 可恢复和不可恢复的异常或错误是什么意思

java - 如何在 Jersey RESTful web 服务中放置 cookie?

node.js - 无法访问 connect-mongo 的原型(prototype)函数