How to implement restart tomcat operation remotely through JAVA?

How to implement restart tomcat operation remotely through JAVA?

1. Join the jcraft package

<dependency>
          <groupId>com.jcraft</groupId>
          <artifactId>jsch</artifactId>
          <version>0.1.54</version>
      </dependency>
 

2. Code implementation class

public class SSHCommandExecutor {
    private String ipAddress;

    private String username;

    private String password;

    public static final int DEFAULT_SSH_PORT = 22;

    private Vector<String> stdout;

    public SSHCommandExecutor(final String ipAddress, final String username, final String password) {
        this.ipAddress = ipAddress;
        this.username = username;
        this.password = password;
        stdout = new Vector<String>();
    }

    public int execute(final String command) {
        int returnCode = 0;
        JSch jsch = new JSch();

        try {
           //Create and connect session.
            Session session = jsch.getSession(username, ipAddress, DEFAULT_SSH_PORT);
            session.setPassword(password);
           //session.setUserInfo(userInfo);

            Properties config = new Properties();

            config.put("StrictHostKeyChecking", "no");

            session.setConfig(config);

            session.connect();

           //Create and connect channel.
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            channel.setInputStream(null);
            BufferedReader input = new BufferedReader(new InputStreamReader(channel
                    .getInputStream()));

            channel.connect();
            System.out.println("The remote command is: " + command);

           //Get the output of remote command.
            String line;
            while ((line = input.readLine()) != null) {
                stdout.add(line);
            }
            input.close();

           //Get the return code only after the channel is closed.
            if (channel.isClosed()) {
                returnCode = channel.getExitStatus();
            }

           //Disconnect the channel and session.
            channel.disconnect();
            session.disconnect();
        } catch (JSchException e) {
           //TODO Auto-generated catch block
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return returnCode;
    }

    public Vector<String> getStandardOutput() {
        return stdout;
    }
 

3. Execution example (restart the tomcat of the remote machine)

public static void main(final String[] args) {
        SSHCommandExecutor sshExecutor = new SSHCommandExecutor(" IP", " ", " ");
       //1  tomcat
        sshExecutor.execute("/usr/java/apache-tomcat-8.5.32/bin/shutdown.sh");
       //2  tomcat
        sshExecutor.execute("/usr/java/apache-tomcat-8.5.32/bin/startup.sh");
        Vector<String> stdout = sshExecutor.getStandardOutput();
        for (String str : stdout) {
            System.out.println(str);
        }
    }
 

Commonly used remote execution channel

There are three commonly used channels, namely ChannelShell, ChannelExec, and ChannelSftp. The first two are used to execute commands (commands can be shell statements or python xxx.py), and the latter are used to upload and download files.

The difference between ChannelShell and ChannelExec: The former is interactive. Before channel.connect(), you need to obtain outputStream and inputStream, then outputstream sends commands, and reads the result of the command from instream (note that after sending the command, before reading the command To wait for a while, you generally need to write a loop judgment, read once per second, set xx seconds to exit according to the actual situation), but there is a disadvantage that it executes like the information printed on the vm, regardless of the execution of the command Any information, it will be returned to the client through instream, and you may only need the result of the command execution; so there is the latter, non-interactive, execute one command at a time (of course, if you have a good combination, you can also Many, anyway, it s just a string, one interaction, secretly telling you that this python script, the command issued to execute this script, can do a lot of things), the advantage is that the information it returns is very clean, only Standard output is returned. Standard error is not returned. At this time, you can use python's print to print the correct information when it is correct, and print the error information when it is wrong, and the client can get the result (because print is standard output).

Steps for usage:

1. New a JSch object;

2. Obtain the Session from the JSch object, use it for connection, and set the connection information (according to the SSH connection principle, there are two ways, one is username + password, the other is username + privatekey + passphrase, the second way is Set in step 1, namely jsch.addIdentity(xxx));

3. Use the session object to call opnChannel("xxx") to open the communication channel and connect;

4. There are different channels and different operations in the back.