Last active
August 3, 2018 18:29
-
-
Save shreve/8cb5fecac60e005461ac4b4ffd1b6903 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env bash | |
log_ssh_connection() { | |
[ -z "$SSH_CONNECTION" ] && echo "It appears you're not connected via SSH" && exit 0; | |
# SSH_CONNECTION="45.77.136.12 44298 10.240.0.6 22" | |
store=/var/log/ssh-logins.log | |
[ ! -e $store ] && sudo touch $store && sudo chmod a+w $store | |
if ! which jq >/dev/null; then | |
sudo apt install jq | |
fi | |
user=$(whoami) | |
remote_addr=$(echo "$SSH_CONNECTION" | cut -f 1 -d' ') | |
location="" | |
ipapi=http://ip-api.com/json | |
slackapi=https://slack.com/api/chat.postMessage | |
fetch_location() { | |
curl --silent $ipapi/$remote_addr | |
} | |
parse_location() { | |
echo $(fetch_location | jq -r '.city,.country') | sed 's/ /, /' | |
} | |
icon() { | |
country=$(fetch_location | jq -r '.countryCode') | |
echo ":flag-$country:" | |
} | |
find_addr() { | |
grep "$user.*$remote_addr" $store >/dev/null | |
} | |
save_addr() { | |
echo -e "$user\t$remote_addr\t$location" >> $store | |
} | |
slack_message() { | |
echo "New login from $user on $HOSTNAME [$location][$remote_addr]" | |
} | |
get_im_channels() { | |
curl --silent \ | |
--data "token=$SLACK_TOKEN" \ | |
https://slack.com/api/users.list | jq -r '.members[] | {id: .id, name: .name}' | |
} | |
post_to_slack() { | |
curl --silent \ | |
--data "token=$SLACK_TOKEN" \ | |
--data "channel=#dev-team" \ | |
--data "username=New Login Alert" \ | |
--data "as_user=false" \ | |
--data "icon_emoji=$(icon)" \ | |
--data "text=$(slack_message)" \ | |
$slackapi | |
} | |
if ! find_addr; then | |
location=$(parse_location) | |
slack_message | |
post_to_slack | |
save_addr | |
fi | |
} | |
log_ssh_connection |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment