如何实现通过JAVA远程执行重启tomcat操作?

1、加入jcraft的包

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

2、代码实现类

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、执行示例(重启远程机器的tomcat)

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);
        }
    }

常用的远程执行通道

常用的有三种通道,即ChannelShell、ChannelExec、ChannelSftp,前两类用于执行命令(命令可以是shell语句,也可以是python xxx.py),后一种是用于上传下载文件。

ChannelShell和ChannelExec的区别: 前者是交互式的,在channel.connect()之前,需要获取outputStream和inputStream,然后outputstream发送命令,从instream中读取命令的结果(注意,发送命令之后,读取命令之前要等待一会儿,一般需要写个循环判断,每秒读一次,根据实际情况设置xx秒超时退出),但是有个坏处是,它执行就像登陆到vm上打印的信息一样,无论执行命令后的任何信息,它都会通过instream返回到客户端来,而你可能仅仅需要命令执行后的结果;于是就有了后者,非交互的,一次通道执行一条命令(当然如果你组合的好,也可以多条,反正就是一个字符串,一次交互,偷偷的告诉你,这一个python脚本,下发的命令去执行这个脚本,可以做好多好多事情哦),好处是,它返回的信息非常干净,只返回标准输出,标准错误是不返回的,这时你可以利用python的print,正确时你print正确信息,错误时print错误信息,客户端都能获取到结果啦(因为print是标准输出)。

使用步骤:

1、new一个JSch对象;

2、从JSch对象中获取Session,用于连接,并设置连接信息(根据SSH的连接原理,有两种方式,一是用户名+密码,二是用户名+privatekey+passphrase,第二种方式要在第1步设置,即jsch.addIdentity(xxx));

3、使用session对象调用opnChannel(“xxx”)打开通信信道,并连接;

4、后面就是不同的channel,不同的操作啦。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值