Key-based SSH script sample

A cluster of servers is an ideal environment for using key-based SSH.

The following Perl script is a trivial scripting example that shouldn’t be implemented, but it demonstrates connecting over an SSH tunnel to servers defined in the variable serverList, running softwareupdate, installing available updates, and restarting the computer if necessary.

The script assumes that key-based SSH was set up for an admin user on all servers to be updated.

#!/usr/bin/perl# \@ is the escape sequence for the "@" symbol.my @serverList = ('admin\@exampleserver1.example.com','admin\@exampleserver2.example.com');foreach $server (@serverList) {open SBUFF, "ssh $server -x -o batchmode=yes 'softwareupdate -i -a' |";while(<SBUFF>) {my $flag = 0;chop($_);#check for restart text in $_my $match = "Please restart immediately";$count = @{[$_ =~ /$match/g]};if($count > 0) {$flag = 1;}} close SBUFF;if($flag == 1) {"ssh $server -x -o batchmode=yes shutdown -r now"}}