Running command after sudo login

2019-01-20 04:13发布

问题:

I'm trying to execute below code to execute sudo commands but I do not know how execute commands after sudo login

String[] commands = {"sudo su - myname;","id"};
JSch jsch = new JSch();
String username = "myuser";
com.jcraft.jsch.Session session = 
        jsch.getSession(username,"hostname", 22);
session.setPassword("my@123");
session.connect();
Channel channel=session.openChannel("exec");
for(int a=0;a<=commands.length;a++){
    ((ChannelExec)channel).setCommand("sudo su - myname;");
    ((ChannelExec)channel).setErrStream(System.err);
    ((ChannelExec) channel).setPty(true);
    channel.connect();
    System.out.println("id *******");
    OutputStream out=channel.getOutputStream();
    out.write(("my@123\n").getBytes());
    out.flush();
    InputStream in=channel.getInputStream();
    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;
        }
    }
}

回答1:

The sudo su executes a new shell.

To provide a command to the shell you either:

  • specify the command on su command-line, like the official JSch Sudo.java example shows:

    ((ChannelExec)channel).setCommand("sudo -S -p '' "+command);
    
  • or feed the command to the shell using its standard input, i.e. the same way you provide the password:

    out.write(("command\n").getBytes());
    

    See also Executing multiple bash commands using a Java JSch program after sudo login.

In general, I recommend the first approach as it uses a better defined API (command-line argument).