美文网首页
监听服务器中某个项目是否挂了

监听服务器中某个项目是否挂了

作者: 仰望星空_4645 | 来源:发表于2019-09-28 21:34 被阅读0次

1、服务器是linux,通过类似xshell访问服务器然后命令查看项目进程是否启动
2、ShellUtils工具类如下

import com.jcraft.jsch.*;

import java.io.*;

public class ShellUtils {
    /**
     * 创建session
     * @param host 主机名称/ip地址
     * @param user 登陆用户名
     * @param psw  密码
     * @param port 端口
     * @return
     */
    public static Session getSession(String host, String user, String psw, int port){
        JSch jsch=new JSch();
        Session session=null;
        try {
            session = jsch.getSession(user, host, port);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.setPassword(psw);
            session.connect();
        } catch (JSchException e) {
            System.out.println("连接linux主机失败");
            e.printStackTrace();
        }
        return session;

    }
    /**
     * 得到可以执行命令的连接
     * @param session 连接session
     * @return 可以执行命令的ChannelExec
     */
    public static ChannelExec getChanel(Session session){
        ChannelExec openChannel=null;
        try {
            if(null !=session){
                openChannel = (ChannelExec) session.openChannel("exec");
            }
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return openChannel;
    }
    /**
     *
     * @param openChannel
     * @param command
     * @return
     */
    public static String getExcRes(ChannelExec openChannel,String command){
        InputStream in =null;
        BufferedReader reader=null;
        StringBuffer result=new StringBuffer();
        try {
            try {
                openChannel.setCommand(command);
                int exitStatus = openChannel.getExitStatus();
                System.out.println(exitStatus);
                openChannel.connect();
                in = openChannel.getInputStream();
                reader = new BufferedReader(new InputStreamReader(in));
                String buf = null;
                while ((buf = reader.readLine()) != null) {
                    result.append(new String(buf.getBytes("gbk"),"UTF-8")+"<br>\r\n");
                }
//reader.close();
            } catch (JSchException e) {
                result.append(e.getMessage());
                e.printStackTrace();
            }
        } catch (IOException e) {
            result.append(e.getMessage());
            e.printStackTrace();
        } /*finally {
//try {
//reader.close();
//} catch (IOException e) {
//e.printStackTrace();
//}
        }*/
        return result.toString();

    }

    public static ChannelShell ChannelShell(Session session) {
        ChannelShell channel = null;
        try {
            if (null != session) {
                channel = (ChannelShell) session.openChannel("shell");
                channel.connect();
            }
        } catch (JSchException e) {
            e.printStackTrace();
        }
        return channel;
    }


    public  static String executeNewFlow(ChannelShell channel, String command) {
        InputStream in =null;
        OutputStream out=null;
        String  msg=null;
        BufferedReader reader=null;
        StringBuffer result=new StringBuffer();
        try {
            in  =  channel.getInputStream();
            out =  channel.getOutputStream();
            out.write(command.getBytes());
            out.flush();
//            reader = new BufferedReader(new InputStreamReader(in));
//            while ((msg =reader.readLine()) !=null ){
//                System.out.println(msg);
//            }
            byte[] tmp=new byte[1024];
            while (true){
                int i=0;
                //线程等待 200ms
                Thread.currentThread().sleep(200);
                while(in.available()>0){
                    i=in.read(tmp, 0, 1024);
                    if(i<0)break;
                }
                System.out.print("------------"+new String(tmp, 0, i));
                return new String(tmp, 0, i);
//                if(channel.isClosed()){
//                    if(in.available()>0) continue;
//                    System.out.println("exit-status: "+channel.getExitStatus());
//                    break;
//                }
            }
        }catch (Exception e){
            result.append(e.getMessage());
            e.printStackTrace();
        }

        return null;
    }

    public static void disConnect(Session session,ChannelExec openChannel){
        if(session!=null&&!openChannel.isClosed()){
            openChannel.disconnect();
        }
        if(session!=null&&session.isConnected()){
            session.disconnect();
        }
    }
}

Test测试类

import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.Session;
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
public class Test {
    private String ip = "101.201.140.161";//服务器ip
    private int port=29xxx;//端口号
    private String user="xxx";//服务器账号
    private String pwd="xxx";//服务器密码
    private String weixin_jiqi="https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=48590c4";//企业微信通知机器
    private String comm="ps -ef|grep axxo;";//查看服务的进程

    @org.testng.annotations.Test
    public void test1(){
        Session session1=ShellUtils.getSession(ip, user, pwd, port);
        ChannelExec chanel=ShellUtils.getChanel(session1);
        String ss=ShellUtils.getExcRes(chanel, comm);
        System.out.println(ss);
        if(ss!=null&&ss.length()>0&&ss.contains("Djava.awt.headless")){
            System.out.println("服务启动中");
//            sendMessage("axxol服务启动中",weixin_jiqi);
        }else{
            System.out.println("服务失败");
            sendMessage("axxol服务挂了",weixin_jiqi);

        }
    }
    /**
     *
     * @param message  消息体内容
     * @param url 机器人的url
     */
    private void sendMessage(String message,String url){
        String reqBody ="{" +
                "    \"touser\":\"12345\"," +
                "    \"msgtype\":\"text\"," +
                "    \"agentid\":1," +
                "    \"text\":{" +
                "        \"content\":\"" +message+
                " \"safe\":1" +
                "}";

        OkHttpClient client = new OkHttpClient.Builder().connectTimeout(10, TimeUnit.SECONDS)// 设置连接超时时间
                .readTimeout(20, TimeUnit.SECONDS)// 设置读取超时时间
                .build();
        MediaType contentType = MediaType.parse("application/json; charset=utf-8");
        RequestBody body = RequestBody.create(contentType, reqBody);
        Request request = new Request.Builder().url(url).post(body).addHeader("cache-control", "no-cache").build();
        Response response = null;
        try {
            response = client.newCall(request).execute();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println();
        }
    }

}

pom.xml需要加入依赖插件

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

    </dependency>
    <dependency>
      <groupId>com.squareup.okhttp3</groupId>
      <artifactId>okhttp</artifactId>
      <version>3.3.0</version>
    </dependency>

3、通过jenkins定时轮询:H/5 9-19 * * *,从9点到19点每隔5分钟轮询一次

效果如下 image.png

相关文章

  • 监听服务器中某个项目是否挂了

    1、服务器是linux,通过类似xshell访问服务器然后命令查看项目进程是否启动2、ShellUtils工具类如...

  • blackbox_exporter的使用

    一、需求 有些时候,我们想监听服务器的某个端口是否存在,监听http的请求是否正确时,这个时候就可以使用 blac...

  • Android 事件监听

    Android中的事件监听,监听某件事件是否触发,如果触发执行之后要进行操作.可以用于某个线程是否执行完毕和监听用...

  • Centos7查看端口占用情况

    1、查看服务器所有被占用端口 2、验证某个端口号是否被占用 3、查看所有监听端口号

  • Vue watch

    Vue中监听某个对象的属性 为了避免监听整个对象导致效率问题,可以监听某个对象的特定属性

  • 部署jar包windows服务工具

    背景 某个周末一个线上项目因为服务器自动重启导致了系统挂了,我们是通过jenkins部署的jar包所以需要手动重启...

  • vue 子组件监听 props 值变化

    监听一个对象 监听对象中的某个值

  • 回车 enter 键盘监听

    JS监听某个输入框 S监听某个DIV区域 JS监听body区域

  • Gunicorn 搭配 Nginx

    拓扑 加装Nginx是否有必要 Nginx作为代理服务器,监听来自外部的80端口的请求;而Gunicorn负责监听...

  • ios动态隐藏、显示ui时的自动布局

    在项目开发中,有时会碰到需要根据服务器返回的数据,来决定界面上显示的某个控件是否需要隐藏的问题。隐藏后,布局要保持...

网友评论

      本文标题:监听服务器中某个项目是否挂了

      本文链接:https://www.haomeiwen.com/subject/navquctx.html