[Trick] Get notification when you excute a long-time-running command

in #linux4 years ago (edited)

image.png

Cause

When we maintain linux server, we sometimes need run a long-time-running command.

Unfortunately we cannot know when the command executes complete.

So we have to check it again and again.

Today I got an idea. Why don't I make a shell to notify me after the command over?

Prepare

It's very easy to do a notification shell program.

I choose Telegram as my notification app. So first we need to create a bot account on Telegram.

Create bot account

Visit Telegram botfather and add it.

Type /help to get all commands of botfather.

image.png

Type /newbot to create a new bot account. Follow the instruction, you will get a bot account.

image.png

After creating the bot, you will get a API token. Please keep it secret.

Get chat id

Then we need to get our chat id. This will be complex.

Currently Telegram doesn't give a tool to get chat id immediately.

We have to set a webhook on the bot account. Then send a message to the bot account.

On the webhook side, we can get the chat id.

In my way, I wrote a sample PHP file(hook.php) on my server.

The code like this:

<?php
file_put_contents('telegram.txt', file_get_contents('php://input'));

And then set the bot account's webhook:

curl -d "url=https://example.com/hook.php" \
    -X POST https://api.telegram.org/bot13*****8:AA********KXAw/setWebhook
  • Replace https://example.com/hook.php with your webhook url.
  • Replace 13*****8:AA********KXAw with your API token.
  • If you don't want to write code, you can use Slack or Discord 's channel webhook.

After setting the webhook, now get in your Telegram to find you bot account.

image.png

Send anything to the bot account and you will find a text file on the webhook server folder.

image.png

You can find the chat id in that file.

Write the notification shell

Now we got all we need, API token and chat id.

We create the notification shell like this:

$ sudo vim /usr/bin/telegram


#!/bin/bash
curl --data-urlencode "text=$1" https://api.telegram.org/bot13*****8:AA********KXAw/sendMessage?chat_id=27****82
echo ""


$ sudo chmod +x /usr/bin/telegram


  • Replace 13*****8:AA********KXAw with your API token.
  • Replace 27****82 with your chat id.

How to use

OK. We finally get our notification shell.

When we run a long-time-running command, we can do like this:

$ wget -c https://files.steem.fans/data/steem_witness_20200918.tar.lz4 | telegram "download command completed"

You will get notification until the command finishes.


Thank you for reading. I'm a witness. I would really appreciate your witness vote! You can vote by SteemLogin. Or open https://steemitwallet.com/~witnesses page, input ety001 to vote.

2.gif

Coin Marketplace

STEEM 0.30
TRX 0.12
JST 0.034
BTC 63960.62
ETH 3142.95
USDT 1.00
SBD 3.95