My requirement is as follow:
I have to login to Unix box using my credentials and once login, I have to do sudo to different user. Once sudo is successful, I have to invoke shell in nohup. On completion of executions, close channel and session both.
I tried the first step which is connect using sudo command, but I don't know how to invoke shell script after the sudo command.
In the below code I am able to execute sudo command, but after getting sudo access how can I execute a shell in nohup with user masteruser
. So that required files created my shell has owner as masteruser
.
public class SSHUploader { Session session = null; public SSHUploader(){ } public void connect(){ try { JSch jsch = new JSch(); session = jsch.getSession("user", "xxx.xxx.xx.xx", 22); session.setPassword("test"); java.util.Properties config = new java.util.Properties(); config.put("StrictHostKeyChecking", "no"); session.setConfig(config); session.connect(); } catch (Exception ex) { ex.printStackTrace(); } } public void executeCommand(String script) throws JSchException, IOException{ System.out.println("Execute sudo"); String sudo_pass = "test"; ChannelExec channel = (ChannelExec) session.openChannel("exec"); ((ChannelExec) channel).setCommand( script); InputStream in = channel.getInputStream(); OutputStream out = channel.getOutputStream(); ((ChannelExec) channel).setErrStream(System.err); channel.connect(); out.write((sudo_pass + "\n").getBytes()); out.flush(); byte[] tmp = new byte[1024]; while (true) { while (in.available() > 0) { int i = in.read(tmp, 0, 1024); if (i