Friday, January 15, 2021

Execute multiple commands one after another in Java


Let's say you want to execute the commands below on a remote Linux machine using a java program to restart program A.

cd /home/projectA
/home/projectA/stopProgramA
/home/projectA/startProgramA

You can use the code below to get them done.

JSch jsch = new JSch();
session = jsch.getSession(username, remoteIPAddress);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();

ChannelExec channelExec = (ChannelExec) session.openChannel("exec");
channelExec.setCommand("cd /home/projectA && /home/projectA/stopProgramA && /home/projectA/startProgramA");

channelExec.setErrStream(System.err);
channelExec.connect();

TimeUnit.SECONDS.sleep(10);
channelExec.disconnect();
channelExec = null;

          session.disconnect();

-----------------------------------------------------------------------------------------------------------------



If you have ever asked the questions below, you will benefit from reading this book.
What is the meaning of life?
Why do I have to suffer?
How can I have the life I like to have?
How can I be the person I want to be?
How can I have good and harmonious relations with others?
What is the true meaning of spiritual practice?  Check it out here.

No comments:

Post a Comment