Bash with json

From test.coolscript.org
Jump to navigation Jump to search

Header[edit]

  • get local ssh ip
ip=`echo $SSH_CONNECTION | cut -d " " -f 1`
#OR
ip=`who am i | cut -d"(" -f2 |cut -d")" -f1`
  • Message Header
Hostname=`hostname`
NOW=$( date '+%F_%H:%M:%S' )

Json[edit]

  • Curl jsdon data
jdata=`curl -s  --connect-timeout 3  --max-time 3 https://api.coolgeo.org?ip=$ip` >/dev/null

Get Json Data using jq (default)[edit]

  • Command-line JSON processor usage in case the command/application is available
country_code=`echo $jdata | jq .country_code  | tr -d '"'`
org=`echo $jdata | jq .org  | tr -d '"'`

Get Json Data using grep[edit]

  • In some cases the jq application is not available, the alternative can be grep

Workaround: Copy json data to random file[edit]

#Create random string
mkrnd=`cat /proc/sys/kernel/random/uuid | sed 's/[-]//g' | head -c 20; echo;`
#Define stat file together with the random string
statfile="/tmp/$mkrnd-ssh-logon.json"
#Copy json to the statfile
echo $jdata > $statfile
#....code stuff
#rm statfile - #delete the statfile when finished

Query sample[edit]

  • Sample to query the ip_type out of our json data:
ip_type=`grep -oP '(?<="ip_type" : ")[^"]*' $statfile` >/dev/null
#Alternative method in case -P is not supported:
#ip_type=`grep -o '"ip_type"\s*:\s"*"[^"]*' $statfile | grep -o '[^"]*$'`

echo $ip_type #(Would return PUBLIC|PRIVATE)

Condition sample[edit]

if [ "$ip_type" = "PUBLIC" ]; then
 #...  code sample
fi

Messaging[edit]

Telegram[edit]

  • Telegram example:
export LANG=C
TELEGRAM_CHAT_ID="xxxxx"
TELEGRAM_BOT_TOKEN="xxxxx"
MESSAGE="$(echo "SSH Login Notification\nHost: $Hostname\nUser: $USER\nIP: $ip\nCountry: $country_code\nOrg: $org\nTime: $NOW")"
/usr/bin/curl --connect-timeout 5 --max-time 10 --silent --output /dev/null \
   --data-urlencode "chat_id=${TELEGRAM_CHAT_ID}" \
   --data-urlencode "text=${MESSAGE}" \
   --data-urlencode "parse_mode=HTML" \
   --data-urlencode "disable_web_page_preview=true" \
   "https://api.telegram.org/bot${TELEGRAM_BOT_TOKEN}/sendMessage"

SMTP[edit]

  • email example
echo  "
UTC Date/Time: $NOW
IP Address: $ip
Country: $country_code
Org: $org
Target Hostname: $Hostname
User: $USER
" | mail -s "SSH Login Alert From: $ip" admin@domain.com