Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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
").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;
        }
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
246 views
Welcome To Ask or Share your Answers For Others

1 Answer

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...