#!/usr/bin/env perl # I'm just assuming the above line works...? # This program presents a list of hard-coded hostnames to the user and lets them ssh to one by choosing it's number # ^^ give love to da maintenance programmer use strict; # Good!! use warnings; # Better!! # It's good practice to identify your globals by making them upper-case our $USER = 'brannont'; our @HOSTS = qw( secdevfdsapp01 dopey bonnie ) ; # Use full path of program for exec to avoid security issues our $SSH_PROGRAM = '/usr/bin/ssh'; # Moved the main program execution up here so the maintenance programmer doesn't have to read the whole program to see what it does... our $SSH_ARGS = &get_ssh_args(); print $SSH_ARGS, "\n" ; exec $SSH_PROGRAM, $SSH_ARGS; # Gets the selected hostname from the user and returns # the arguments we'll need to pass to the 'ssh' command sub get_ssh_args { my $chosen_hostname = &choose_host(); return &ssh_string($chosen_hostname) ; } # For a given host, return the ssh arguments to allow us to # login as a hard-coded user on that host sub ssh_string { my $host = shift; # Suggest also appending your domain here: return &username() . "@" . $host . &domain(); # 'Programming Perl' suggests avoiding use of printf() # sprintf "%s@%s", $user, $host } # Prints the list of hosts with numbers in front to allow # user to make a selection sub printchoices { print "\n\n", "ssh hosts\n", "---------\n"; for (my $i=0; $i < &num_hosts(); ++$i) { print "[$i] ", &hostname_by_num($i), "\n" ; } } # prints a prompt for user input sub prompt { return "\n\nssh to: " ; } # Gets the user's chosen host sub getchoice { print &prompt(); my $choice = ; chomp $choice; return $choice; } # Get the user's chosen host (by number) or die trying # renamed from 'mainloop' sub choose_host { my $chosen_host; while ( !$chosen_host ) { &printchoices(); my $user_choice = &getchoice(); if( ($user_choice =~ /^\d+$/) && ($user_choice >= 0) && ($user_choice < &num_hosts()) ) { $chosen_host = $user_choice; } } # May as well dereference the name here... return &hostname_by_num($chosen_host); } # These three functions are simple lookups to the globals # now, but in the future they can be expanded sub num_hosts { return scalar(@HOSTS); } sub hostname_by_num { return $HOSTS[ $_[0] ]; } sub username { return $USER; } # In the future, this could return our domain # eg. ".example.com", possibly from a global sub domain { return ""; }