Hooli
Hooli

Reputation: 1195

run multiple commands on remote server

So far I've managed to connect, run a single command and then disconnect. The problem I'm having is running a second, third, etc command thereafter.

public static void main(String args[]) {
        try {
            JSch js = new JSch();
            Session session = js.getSession("myuser", "myhost", 22);
            session.setPassword("mypassword");
            Properties properties = new Properties() {
                {
                    put("StrictHostKeyChecking", "no");
                }
            };
            session.setConfig(properties);
            session.connect();

            Channel channel = session.openChannel("exec");

            ChannelExec channelExec = (ChannelExec) channel;
            channelExec.setCommand("ls");
            channelExec.setErrStream(System.err);
            channelExec.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

//            This part doesn't work. It causes the program to hang.
//            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(channelExec.getOutputStream()));
//            writer.write("cd Downloads");
//            writer.write("ls");
//            reader = new BufferedReader(new InputStreamReader(channelExec.getInputStream()));
//            while ((line = reader.readLine()) != null) {
//                System.out.println(line);
//            }

            channelExec.disconnect();
            session.disconnect();

            System.out.println("Exit code: " + channelExec.getExitStatus());
        } catch (JSchException | IOException ex) {
            Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

I've tried using the ChannelExec OutputStream but that just caused the program to do nothing so I suspect that's not the way to go.

What should I add to print the contents following the commands cd Downloads and ls for example after the first ls output has been printed?

Upvotes: 0

Views: 1238

Answers (1)

Anup Jha
Anup Jha

Reputation: 11

Seperate your commands with ";" eg:

String command1="cd mydeploy/tools/Deploy/scripts/; ls -ltr;./conn_testing.ksh";

Upvotes: 1

Related Questions