LoginSignup
8
9

More than 5 years have passed since last update.

コマンド実行が終わったことをぼっちslackに通知するハック

Last updated at Posted at 2016-01-15

概要

  • 実行に時間がかかるコマンドを打った時、長々と実行ログを眺めるのは時間の無駄。
  • かといって、次のタスクにとりかかっていると、実行したことを忘れてしまう。。

という課題を解決するために、任意のコマンド実行が終了したら、ぼっちslackに通知してくれるようにしました。

シンプル編

方針

  • command; [slack通知]で実行が終わったらメッセージを送るシンプルな仕組み
  • commandの後ろにちょろっと足すだけで通知できるようにしたい(つまり、なんかのスクリプトの引数として、実行したいcommandを入力するのは使いづらいので避ける)

実装

  • 事前準備として、ぼっちslackのwebhookのurlを発行しておく。slack webhookとかで検索すれば、やり方はすぐ出てくるので割愛します。

  • slackを送るperlスクリプト

send_to_slack.pl
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long qw(:config posix_default no_ignore_case gnu_compat);
use LWP::UserAgent;
use JSON::XS;

my $uri_str = 'https://hooks.slack.com/services/YOUR_BOCCHI_SLACK_WEBHOOK';


GetOptions(
    'message=s' => \my $MESSAGE,
);

my $params = +{
    text => $MESSAGE,
};
my $paylaod_json = JSON::XS->new->encode($params);

my $ua  = LWP::UserAgent->new;
my $req = HTTP::Request->new(POST => $uri_str);
$req->content_type('application/x-www-form-urlencoded');
$req->content(sprintf("payload=%s",$paylaod_json));

$ua->request($req);
  • .zshrcの設定
alias -g N='; ~/myscript/send_to_slack.pl --message 終わったよー'

使い方

dev/tools/sync_to_servers.pl N

しばらくたった後...

スクリーンショット 2016-01-15 15.42.08.png

これで実行後のタスクを忘れることを防ぐ。

応用編

改善点

  • 一連の作業をバックグラウンドでやりたい
  • メッセージになんのスクリプトだったか加えたい

実装

  • プロセス簡易監視 && slackに送るperlスクリプト
notify_process_end_to_slack.pl
#!/usr/bin/env perl
use strict;
use warnings;
use Getopt::Long qw(:config posix_default no_ignore_case gnu_compat);
use LWP::UserAgent;
use JSON::XS;

my $uri_str = 'https://hooks.slack.com/services/YOUR_BOCCHI_SLACK_WEBHOOK';

GetOptions(
    'pid=i'     => \my $PID,
);

die "can't watch!\n" unless $PID;

my $program_name = '';
while (1) {
    if (my $name = `ps -p $PID -o comm=`) {
        chomp $name;
        $program_name ||= $name;
        sleep 1;
    } else {
        last;
    }
}

my $message = "${program_name}終わったよー";
my $params = +{
    text => $message,
};
my $paylaod_json = JSON::XS->new->encode($params);

my $ua  = LWP::UserAgent->new;
my $req = HTTP::Request->new(POST => $uri_str);
$req->content_type('application/x-www-form-urlencoded');
$req->content(sprintf("payload=%s",$paylaod_json));

$ua->request($req);
  • .zshrcの設定
alias -g NB='>/dev/null 2>&1 & ~/myscript/notify_process_end_to_slack.pl --pid $! &'

補足

  • ps -p [PID] -o comm= で該当のプロセスIDのプログラム名を取得できます
  • $! には直前にバックグラウンド実行したPIDが入ります

使い方

hoge.pl NB

コマンドをバックグラウンドで実行してくれる。
しばらくすると、

スクリーンショット 2016-01-15 15.58.09.png

注意したいのは、これが使えるのは、実行したいコマンドがバックグラウンド実行可能なときだけ。
例えばssh -t user@other_host 'any_command' NBができない。実行したいプロセスがsuspendになる。

8
9
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
9