0

I have a problem with my code. I'm trying to become to root with sudo su - but when execute it standby the console, it show me this:

Connected

#

And there not pass the next line.

This my code:

String command1 = "sudo su -";

try {

    java.util.Properties config = new java.util.Properties();
    config.put("StrictHostKeyChecking", "no");
    JSch jsch = new JSch();
    Session 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);

    OutputStream out = channel.getOutputStream();
    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 (Exception e) {
    e.printStackTrace();
}
jww
  • 97,681
  • 90
  • 411
  • 885
  • When you do sudo su, it will ask for password. – Sambit Nov 16 '19 at 16:03
  • replace your command with `sudo su -u username`. I think this will solve your issue. – ialam Nov 16 '19 at 16:05
  • 1
    This has been asked many times already. Please google your problem before posting a question. -- See for example [Running command after sudo login](https://stackoverflow.com/q/41670999/850848) or [Executing sudo using SSH “exec” channel in JSch](https://stackoverflow.com/q/52481755/850848). – Martin Prikryl Nov 16 '19 at 16:21

1 Answers1

0

sudo su - command opens a new shell process inside your current shell.

This new shell process will not end until it receives an exit command.

Since you are issuing commands from Java to another process in the OS, the result is the same as if you issued a command that hanged.

There are two ways to work around this:

  1. Use sudo only to execute the exact commands you really need by appending sudo to every command.

  2. Create a wrapper script that will execute all commands you need to run as root and run that with sudo.

Lev M.
  • 6,088
  • 1
  • 10
  • 23
  • @AntonioRomeroElvira glad to hear the solution worked for you. Could you pleas mark the answer as "accepted". Thanks. – Lev M. Nov 20 '19 at 20:28