Skip to content

Instantly share code, notes, and snippets.

@ypsilon-takai
Last active June 6, 2023 12:48
Show Gist options
  • Save ypsilon-takai/7a27e0963518e5f6417e458ca5399181 to your computer and use it in GitHub Desktop.
Save ypsilon-takai/7a27e0963518e5f6417e458ca5399181 to your computer and use it in GitHub Desktop.
本社サーバのIPをslackにポストするスクリプト
# 本社サーバのIPをslackにポストするスクリプト
import requests
import yaml
import pathlib
HOME = pathlib.Path('/home/manage')
SLACK_INFO = HOME / 'ipreport/slack_info.yaml'
CIP = HOME / 'ipreport/current_ip.txt'
def read_credencials():
with open(SLACK_INFO, mode='r') as conf:
conf = yaml.safe_load(conf)
return conf
def get_gip():
# gip == global ip
gip_checker = 'http://ifconfig.io/ip'
res = requests.get(gip_checker)
if res.status_code != 200:
gip = 'global ip get errror'
else:
gip = res.text.strip()
return gip
def push_msg2slack(token, chan, message):
slack_post_url = "https://slack.com/api/chat.postMessage"
headers = {
f"Authorization": f"Bearer {token}",
"Content-Type": "application/json; charset=utf-8"
}
data = {
'channel': chan,
'text': message
}
res = requests.post(slack_post_url, headers=headers, json=data)
return res
def read_saved_ip():
cip = 'none'
if CIP.exists():
with open(CIP, mode='r') as f:
cip = f.readline().strip()
return cip
def save_ip(ip):
with open(CIP, mode='w') as f:
f.write(ip)
if __name__ == '__main__':
import sys
import syslog
run_type = sys.argv[1]
run_time = sys.argv[2]
syslog.syslog(syslog.LOG_INFO, f"{run_time}: runtype:{run_type}")
info = read_credencials()
token = info['token']
chan = info['channel-id']
global_ip = get_gip()
if run_type == "check":
c_ip = read_saved_ip()
if global_ip == c_ip:
syslog.syslog(syslog.LOG_INFO, "IP は変っていませんでした。")
else:
message = f'本社サーバのIPが変更されました!: {global_ip}'
save_ip(global_ip)
res = push_msg2slack(token, chan, message)
#print("return ", res.json())
syslog.syslog(syslog.LOG_INFO, f"IPが変更されました。 旧:{c_ip} 新:{global_ip}")
elif run_type == "report":
message = f'本社サーバのIPはこれです: {global_ip}'
save_ip(global_ip)
res = push_msg2slack(token, chan, message)
#print("return ", res.json())
# debug
syslog.syslog(syslog.LOG_INFO, f"IPを通知しました {global_ip}")
# report_global_ipをcronで起動するためのシェル
datetime=$(date +%Y%m%d-%H%M%S)
basedir=/home/manage/work/ip_reporter
source ${basedir}/venv/bin/activate
if [[ $1 == report ]]; then
python ${basedir}/report_global_ip.py report $datetime
elif [[ $1 == check ]]; then
python ${basedir}/report_global_ip.py check $datetime
else
echo "Invalid arguments."
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment