Skip to content

Instantly share code, notes, and snippets.

@nitefood
Last active March 28, 2023 09:07
Show Gist options
  • Save nitefood/70988e6afcd1c5895a6dfe9137f1538e to your computer and use it in GitHub Desktop.
Save nitefood/70988e6afcd1c5895a6dfe9137f1538e to your computer and use it in GitHub Desktop.
parallel remote tail
#!/usr/bin/env bash
# ssh targets and log search pattern
user="root" # remote ssh user
hostlist="host1.example.com host2.example.com host3.example.com" # space-separated ssh hosts list
remote_logfile="/var/log/syslog"
search_pattern="Session" # can use regexps here (grep -E)
# trap ctrl-c for named pipe cleanup and ssh process killing
trap 'echo -e "\n\nCleaning up..."; for pid in $children; do kill -9 $pid 2>/dev/null; done; rm "$HOME/tailpipe"; exit 0' INT
mkfifo "$HOME/tailpipe" # create named pipe to read remote tail output from
children=""
for host in $hostlist; do
# establish ssh connection to the hosts and launch the remote command
# use colored hostname prefix for every logline to clearly highlight the host where the log line is from
remote_command='tail -f '"$remote_logfile"' | while read logline; do printf "\e[38;5;'"$((1+$RANDOM%228))"'m%-25s\e[0m $logline" "[$HOSTNAME]"| grep -E "'"$search_pattern"'"; done'
ssh $user@$host "$remote_command" 1>"$HOME/tailpipe" 2>/dev/null & # launch the ssh command
[[ -n "$children" ]] && children+=" $!" || children+="$!" # save the ssh child PID in order to clean it up at ctrl-c time
done
cat < "$HOME/tailpipe" # read remote log lines from the named pipe
@nitefood
Copy link
Author

nitefood commented Dec 3, 2020

Output for three servers looks like this:

immagine

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment