Skip to content

Instantly share code, notes, and snippets.

@SSARCandy
Last active November 11, 2018 13:30
Show Gist options
  • Save SSARCandy/52ee4a7f5613f812434af158e46e28aa to your computer and use it in GitHub Desktop.
Save SSARCandy/52ee4a7f5613f812434af158e46e28aa to your computer and use it in GitHub Desktop.
Using pdsh to fetch multiple servers status and output JSON format data
#!/bin/bash
status_file='./status'
status_json_file='./status.json'
hosts="cml[4,22]"
cmd_hostname="cat /etc/hostname | tr '\n' ','"
cmd_uptime_and_avgload="uptime | sed 's/[0-9]*:[0-9]*,//' | sed 's/.*up//' | sed 's/load average://' | tr '\n' ','"
cmd_cpuinfo="cat /proc/cpuinfo | grep processor | wc -l | tr '\n' ','"
cmd_meminfo="cat /proc/meminfo | egrep '^MemTotal|^MemAvailable|^SwapTotal|^SwapFree|^Cached' | tr 'kB' ' ' | awk -F ':' '{printf(\$2\",\")}'"
cmd_lastupdate="date +'%H:%M:%S'"
function fetch_info {
cmd="$cmd_hostname; $cmd_uptime_and_avgload; $cmd_cpuinfo; $cmd_meminfo; $cmd_lastupdate"
header="Server,Uptime,Users,1m Load,5m Load,15m Load,CPU cores,MemTotal,MemAvailable,SwapTotal,SwapFree,Cached,Update Time"
echo $header > $status_file
pdsh -w $hosts -N -R ssh $cmd >> $status_file
cat $status_file | jq -sR '[sub("\n$";"") | splits("\n") | sub("^ +";"") | [splits(",")]] | .[0] as $header | .[1:] | [.[] | [. as $x | range($header | length) | {"key": $header[.], "value": $x[.]|sub("^ +";"")}] | from_entries]' > $status_json_file
}
while true;
do
fetch_info
sleep 5
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment