简体   繁体   English

使用 bash 脚本将实时 output 发布到 Slack

[英]Post real time output to Slack with bash script

I have a python script that I am executing with cron job.我有一个 python 脚本,我正在使用 cron 作业执行该脚本。 This script generates some output while executing and I wish to post it to Slack channel in real time.该脚本在执行时会生成一些 output,我希望将其实时发布到 Slack 频道。

Here is a bash script that I have:这是我拥有的 bash 脚本:

#!/bin/bash

log_file=logs_$(date '+\%Y-\%m-\%d_\%H:\%M').txt

cd /path/to/script/run.py > /path/to/logs/${log_file} 2>&1 

cat /path/to/logs/${log_file} | while read LINE; do
  (echo "$LINE" | grep -e "Message" ) && curl -X POST --silent --data-urlencode \
    "payload={\"text\": \"$(echo $LINE | sed "s/\"/'/g")\"}" "https://hooks.slack.com/services/xxxxxx";
done

This scrip works but it of course posts all messages to slack once the python script has already been executed.此脚本有效,但是一旦 python 脚本已经执行,它当然会将所有消息发布到 slack。 Is there any way I could configure it so that messages would be sent to Slack in real time while the python script is still being executed?有什么方法可以配置它,以便在 python 脚本仍在执行时实时将消息发送到 Slack?

You may be able to read the output from your run.py script via process substitution:您可以通过进程替换从run.py脚本中读取 output:

#!/bin/bash

log_file=logs_$(date '+\%Y-\%m-\%d_\%H:\%M').txt

while read -r line ; do
    echo "$line"
    (echo "$line" | grep -e "Message" ) && curl -X POST --silent --data-urlencode \
        "payload={\"text\": \"$(echo $line | sed "s/\"/'/g")\"}" "https://hooks.slack.com/services/xxxxxx";
done < <(/path/to/script/run.py 2>&1) >> "$log_file"

It may also prove useful to paste your code into shellcheck.net and have a look at the suggested changes.将您的代码粘贴到 shellcheck.net 并查看建议的更改也可能很有用。

Your script shouldn't work at all as you're not executing run.py but you're changing your working directory into it, so unless run.py is a directory, your script should fail.您的脚本根本不应该工作,因为您没有执行run.py但您正在将工作目录更改为它,因此除非run.py是一个目录,否则您的脚本应该会失败。

Also, commands in bash scripting are executed sequentially, so if you launch your python command and then read the log, no wonder that you're not getting log lines in real time.此外,bash 脚本中的命令是按顺序执行的,因此如果您启动 python 命令然后读取日志,难怪您没有实时获取日志行。

What i would do is using some pipes and xargs:我要做的是使用一些管道和xargs:

#!/bin/bash

/path/to/script/run.py | grep -e "Message" | sed "s/\"/'/g" | xargs -I{} curl -L -X POST --silent --data-urlencode 'payload={"text":"{}"}' https://hooks.slack.com/services/xxx

I've added -L to the curl command because hooks.slack.com makes a redirect to api.slack.com and without that flag curl will stop after the 302 instead of following the Location header in the response. I've added -L to the curl command because hooks.slack.com makes a redirect to api.slack.com and without that flag curl will stop after the 302 instead of following the Location header in the response.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM