Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple commands using JSch

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 < 0)
                    break;
                System.out.print(new String(tmp, 0, i));
            }
            if (channel.isClosed()) {
                System.out.println("exit-status: " + channel.getExitStatus());
                break;
            }
            try {
                Thread.sleep(1000);
            } catch (Exception ee) {
                System.out.println(ee);
            }
        }
        channel.disconnect();
        System.out.println("Sudo disconnect");
    }

    public void disconnect(){
        session.disconnect();
    }


    public static void main(String... args) throws JSchException, IOException {

        SSHUploader up = new SSHUploader();
        up.connect();

        up.executeCommand("sudo -u masteruser bash");

        up.disconnect();
    }

}
like image 462
user1251973 Avatar asked Jun 27 '13 20:06

user1251973


People also ask

How do I run multiple commands in JSch?

Executing multiple commands at once on the remote server using Jsch. We must add a semicolon(;) between each command we want to run. So, the format will be first_command;second_command;third_command.

How run multiple Unix commands in Java?

Say if you want to scan file(s) using antivirus you have to use shell command in java program. command[2] = "f: && dir && cd snap"; will execute three command. Use && in string to use multiple command.

What is Jcraft JSch?

JSch is a pure Java implementation of SSH2. JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.


2 Answers

For executing multiple commands in sequence, you can create a command string like below:

String script ="pbrun su - user; cd /home/scripts;./sample_script.sh”

Execute it and pass this string to your method above.

like image 183
Sumit Sharma Avatar answered Oct 04 '22 14:10

Sumit Sharma


The post may be old, but I found another easy way that allows you to retrieve the output of each command separately. Note that this code has to be executed once the session has been opened, as shown in the examples (http://www.jcraft.com/jsch/examples/Exec.java.html):

for (String command : commands) {
    ChannelExec channel = (ChannelExec) session.openChannel("exec");
    channel.setInputStream(null);
    channel.setErrStream(System.err);
    channel.setCommand(command);
    channel.connect();
    printOutput(channel);
    channel.disconnect();
}

Where printOutput uses channel.getInputStream() to read the result of the command.

like image 20
yanneke Avatar answered Oct 04 '22 13:10

yanneke