Running command after sudo login

2019-01-20 03:52发布

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条回答
走好不送
2楼-- · 2019-01-20 04:23

The sudo su executes a new shell.

To provide a command to the shell you either:

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

查看更多
登录 后发表回答