[PYTHON] I created a Slack bot that confirms and notifies AWS Lambda of the expiration date of an SSL certificate

Introduction

Currently, the SSL certificate of the server I have privately is set with Let's Encrypt. Let's Encrypt will notify you by e-mail about the expiration date of the certificate, but if it is an e-mail, it may be buried with other e-mails and omission of confirmation may occur.

** If you update it automatically, yeah! I think there is something like **, but this time I will ignore it

environment

local

AWS

Repository

https://github.com/nnsnodnb/slackbot_ssl_expiration

Preparation

ʻSet Bots in Apps & integrations`

Bots___ひやかしプロジェクト_Slack.png

Library

requirements.txt


appdirs==1.4.3
packaging==16.8
pyparsing==2.2.0
requests==2.13.0
six==1.10.0
slacker==0.9.42

Sample source

bot.py


from slacker import Slacker
import datetime
import socket
import ssl
import slack_settings #Slack in the same directory_settings.Place py


slack = Slacker(slack_settings.SLACK_API_TOKEN)


def ssl_valid_time_remaining(hostname):
    expires = ssl_expiry_datetime(hostname)
    return expires - datetime.datetime.utcnow()


def ssl_expires_in(hostname, buffer_days=7):  #Deadline branch 7 days in advance
    remaining = ssl_valid_time_remaining(hostname)
    if remaining < datetime.timedelta(days=0):
        raise AlreadyExpired("Cert expired %s days ago" % remaining.days)
    elif remaining < datetime.timedelta(days=buffer_days):
        return True
    else:
        return False


def ssl_expiry_datetime(hostname):
    ssl_date_fmt = r'%b %d %H:%M:%S %Y %Z'
    context = ssl.create_default_context()

    conn = context.wrap_socket(
            socket.socket(socket.AF_INET),
            server_hostname=hostname,
    )

    conn.settimeout(3.0)
    conn.connect((hostname, 443))
    ssl_info = conn.getpeercert()
    return datetime.datetime.strptime(ssl_info['notAfter'], ssl_date_fmt)  # ssl_info['notAfter']Is the expiration date of the certificate


def post_slack(hostname):
    message = '@channel https://' + hostname + ' '
    if ssl_expires_in(hostname):
        message += 'It's about time to get rid of'
    else:
        message += 'Is still within the deadline' 

    #Methods around here use the slacker package
    slack.chat.post_message(
            '#expiration',
            message,
            as_user=True,
            link_names=True
    )


def execute(event, context):
    post_slack('<YOUR DOMAIN>')

slack_setting.py


SLACK_API_TOKEN = ''

Run locally

$ python bot.py

スクリーンショット_2017-06-07_17_21_48.png

This time again, Mr. You Watanabe was in charge of the notification.

Lambda settings

Lambda_Management_Console.png

  1. Trigger settings Lambda_Management_Console.png Set as you like. I have selected the setting to be notified by cron at 2:00 AM from Monday to Friday.
  2. Enter the function name appropriately
  3. Select Python 3.6 for runtime
  4. Source code upload is explained below
  5. Enter bot.execute for handler
  6. Roll etc. are set individually

Reflection of external library

In the local environment, the following commands etc. are quite good, but

Local environment


$ pip install -r requirements.txt

Since the library is not recognized on AWS Lambda, you need to upload the entire external library.

Save the external library in the project directory


$ pip install <LIBRARY_NAME> -t .

If you do something like that, it will be saved in the project directory. However, it is troublesome to do it one by one, so I did the following.

$ pip freeze > requirements.txt  # requirements.Without txt
$ pip install -r requirements.txt -t .

Then zip and upload

$ zip -r bot.zip *  # bot.zip is your favorite name

There is a bot.zip in the project directory, so selectUpload.ZIP file to upload the bot.zip`.

スクリーンショット 2017-06-07 17.41.57.png

If you set it up properly, you should be notified to Slack at the set time! In my environment, You Watanabe will inform you from Monday to Friday 2:00 AM as mentioned above! !!

Recommended Posts

I created a Slack bot that confirms and notifies AWS Lambda of the expiration date of an SSL certificate
Script to get the expiration date of the SSL certificate
I created a Slack bot that confirms and notifies AWS Lambda of the expiration date of an SSL certificate
I made a slack bot that notifies me of the temperature
I wrote a Slack bot that notifies delay information with AWS Lambda
[Discode Bot] I created a bot that tells me the race value of Pokemon
I made a github action that notifies Slack of the visual regression test
Script to get the expiration date of the SSL certificate
I built an application with Lambda that notifies LINE of "likes" using the Qiita API
I wrote AWS Lambda, and I was a little addicted to the default value of Python arguments
[AWS] Detects the specified character string from the Lambda execution log and notifies slack
I made a Linebot that notifies me of nearby evacuation sites on AWS
A program that notifies slack of the operating status of fully automatic botanical photography equipment
Make a BOT that shortens the URL of Discord
LINE Bot that notifies you of the stocks of interest
I made an IFTTT button that unlocks the entrance 2 lock sesame with 1 button (via AWS Lambda)
When I created an ECR scan from a CDK, I could see the back side of the scan
How to make an interactive LINE BOT 004 (answer the closing date of a listed company)
The story that I set transparent proxy and it worked for some reason without a certificate
The story of creating a bot that displays active members in a specific channel of slack with python
I made a LINE bot that tells me the type and strength of Pokemon in the Galar region with Heroku + Flask + PostgreSQL (Heroku Postgres)
A story that I was addicted to calling Lambda from AWS Lambda.
A formula that simply calculates the age from the date of birth
Create an app that notifies LINE of the weather every morning
[Python] I wrote a REST API using AWS API Gateway and Lambda.
[For beginners] I want to get the index of an element that satisfies a certain conditional expression
(Python) I made an app from Trello that periodically notifies slack of tasks that are about to expire.
Use AWS lambda to scrape the news and notify LINE of updates on a regular basis [python]
Create a bot that posts the number of people positive for the new coronavirus in Tokyo to Slack
I did a preliminary survey of the API that receives Zoom meeting entry / exit webhooks on Lambda (1)