Saturday, March 24, 2018

Running same set of commands on multiple servers using for loop

Developers as usual are very lazy and so instead of going to each server to grep for an error string in the log file and creating a report, here is a simple way to collect all the necessary log lines.
Create a file containing a list of server names on which we want to check the logs - one on each line and then run this for loop if using bash:

for s1 in $(cat servers_list.txt); do
  ssh -q ${s1} "grep 'search_string' /search/folder/*/*.log* | sed 's/^/${s1} => /'" >> /tmp/search.log
  # Other commands here if required
done

If you are using csh, then the for loop syntax is slightly different:

foreach s1 in (cat servers_list.txt)
  ssh -q ${s1} "grep 'search_string' /search/folder/*/*.log* | sed 's/^/${s1} => /'" >> /tmp/search.log
  # Other commands here if required
end

The code is simple - for each server, ssh to that server and run the grep command to find out the log lines having the specific string. The bigger trick here is to use sed to pre-pend server name to the grepped log line to make the report useful. This should return a file with lines in the format:

server_name => [log line grepped from the log file]

No comments:

LinkWithin

Related Posts Plugin for WordPress, Blogger...