LoginSignup
1
1

AWSのboto3を使ってサーバのコマンド結果をSQSのキューに飛ばしてSNSでメール送信してみた

Last updated at Posted at 2018-10-25

やりたいこと

  1. AWS上のEC2(Linux)で一定時間毎に自動的にコマンドを叩く。
  2. コマンドの標準出力をメールで飛ばす。ついでにSQSにも連携しとく。

方法

  • pythonのboto3を用いて、SNSでメールを飛ばす。
  • SQSへはSNSのサブスクリプションで連携する。

前提

  • EC2を立てる(ここでのサーバはRHEL系を想定してます。)
  • EC2にaws cli、python3、boto3のインストール。
  • aws configureでユーザ認証。
  • SNSでトピック及びサブスクリプション作成。
  • SQSでキュー作成。

コード

EC2上で以下のスクリプトを作成。
実行するコマンドやSNSのトピックはXXXXX表記ですので、適宜置き換えて下さい。あと、変数はテキトーです(笑)。

### send_msg.py ###

import boto3
import subprocess
import shlex
import time

# SNSのトピックのARNを記載
sns = boto3.resource('sns')
topic = sns.Topic('arn:aws:sns:ap-northeast-1:XXXXXXXX:topic-name')

def execute_command_and_publish(cmd):
    process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)
    output = process.stdout.read()
    decoded_output = output.decode("UTF-8")
    
    response = topic.publish(Message=decoded_output)
    print(response)

# 出力させたいコマンドを指定
cmd = "XXXXXXX"
execute_command_and_publish(cmd)

# ループ処理(ここでは1分毎に定期実行)
while True:
    execute_command_and_publish(cmd)
    time.sleep(60)

参考にしたもの

以下参考にさせていただきました。ありがとうございました。
AWS SDKを使ってSNSにCPU使用率を送りつける
boto3 (AWS SDK for Python) メモ - Qiita
boto3を使ってAmazon SNSへpublishしてみた | DevelopersIO

1
1
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
1
1