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;
}
}
}