钉钉机器人远程重启系统服务

from flask import Flask, request
import subprocess

app = Flask(__name__)

@app.route('/send_message', methods=['GET'])
def send_message():
    webhook_url = 'https://oapi.dingtalk.com/robot/send?access_token=YOUR_TOKEN'    # YOUR_TOKEN是钉钉机器人的hook
    message = '''
    {
        "msgtype": "actionCard",
        "actionCard": {
            "title": "重启Odoo服务",
            "text": "点击下方按钮以重启Odoo服务。",
            "btnOrientation": "0",
            "singleTitle": "重启Odoo",
            "singleURL": "http://your-server-ip:5000/webhook"  
        }
    }
    '''
    curl_command = f"curl '{webhook_url}' -H 'Content-Type: application/json' -d '{message}'"
    result = subprocess.run(curl_command, shell=True, capture_output=True, text=True)
    return result.stdout

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5001)

上面这段代码将发送一个消息卡片到钉钉群,用户点击卡片中的按钮后,将触发监听服务。

先安装这个库: pip install flask

上面的文件名为:send_message.py

这段代码将监听来自钉钉的消息,并在接收到特定消息时,重启Odoo服务。

# 导入必要的库
from flask import Flask, request, jsonify
import subprocess

# 创建Flask应用实例
app = Flask(__name__)

# 定义路由,处理钉钉机器人的消息
@app.route('/webhook', methods=['POST'])
def webhook():
    # 获取请求中的JSON数据
    data = request.json
    # 检查数据是否包含特定文本内容
    if 'text' in data and 'content' in data['text']:
        content = data['text']['content']
        # 如果内容包含"重启odoo",则执行重启命令
        if '重启odoo' in content:
            try:
                # 执行重启Odoo服务的命令
                subprocess.run(['sudo', 'systemctl', 'restart', 'odoo12.service'], check=True)
                return jsonify({"msgtype": "text", "text": {"content": "Odoo服务已重启"}})
            except subprocess.CalledProcessError:
                return jsonify({"msgtype": "text", "text": {"content": "重启Odoo服务失败"}})
    return jsonify({"msgtype": "text", "text": {"content": "无效的命令"}})

# 运行Flask应用
if __name__ == '__main__':
    app.run(host='0.0.0.0', port=5000)

 

  这个文件名为: webhook_listener.py
 下面为上面的脚本来封装成服务
通过systemd来管理和运行您的服务,确保它们在后台运行并在系统启动时自动启动。

创建systemd服务文件

为监听服务创建/etc/systemd/system/webhook_listener.service

 

[Unit]
Description=Gunicorn instance to serve webhook_listener
After=network.target

[Service]
User=your_user
Group=www-data
WorkingDirectory=/path/to/your/application
ExecStart=/usr/local/bin/gunicorn --workers 3 --bind 0.0.0.0:5000 webhook_listener:app

[Install]
WantedBy=multi-user.target
为Web接口服务创建/etc/systemd/system/send_message.service
[Unit]
Description=Gunicorn instance to serve send_message
After=network.target

[Service]
User=your_user                    # 这个是系统的用户 比如:root  odoo  user 等等
Group=www-data
WorkingDirectory=/path/to/your/application     # 这个是文件所在的目录
ExecStart=/usr/local/bin/gunicorn --workers 3 --bind 0.0.0.0:5001 send_message:app

[Install]
WantedBy=multi-user.target

 

启动并启用服务:

1、启动服务

sudo systemctl start webhook_listener
sudo systemctl start send_message

2、启用服务使其在系统启动时自动运行

sudo systemctl enable webhook_listener
sudo systemctl enable send_message

 

 

 这里的 203.0.113.1 是您远程服务器的公网IP地址。这个IP地址用于确保您的手机浏览器可以通过互联网访问您的服务器。

详细说明

1. 公网IP地址

  • 公网IP地址:这是您服务器的互联网可访问地址。任何连接到互联网的设备都可以使用这个IP地址来访问您的服务器。

2. 使用公网IP地址的原因

  • 可访问性:通过公网IP地址,您的手机浏览器可以访问服务器上的应用,从而触发发送消息卡片到钉钉群的操作。
  • 钉钉机器人回调:当用户在钉钉群中点击按钮时,钉钉机器人需要向您的服务器发送HTTP请求,这也需要使用公网IP地址,以确保钉钉能够访问您的服务器

 

 
sudo journalctl -f -u send_message.service   实时查看systemd服务的日志。这是默认的,如果send_message.service中如果有设置。

 

 

 

 

 

posted @ 2024-06-05 18:02  *感悟人生*  阅读(4)  评论(0编辑  收藏  举报