Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@objectiveSee
Last active August 29, 2015 14:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save objectiveSee/2b3d46e4fe887518bd56 to your computer and use it in GitHub Desktop.
Save objectiveSee/2b3d46e4fe887518bd56 to your computer and use it in GitHub Desktop.
usage: ./ssh.pl or ./ssh.pl <index of host>
#!/usr/bin/perl
use strict;
use warnings;
# Read SSH config
my $filename = '/Users/<your user>/.ssh/config';
open(my $fh, '<:encoding(UTF-8)', $filename)
or die "Could not open file '$filename' $!";
# Iterate file by line, and find hosts using regular expression
my @hosts = ();
while (my $row = <$fh>) {
chomp $row;
my ($host) = $row =~ /^Host (.*)$/;
if ($host) {
my $arraySize = @hosts;
print "$arraySize: $host\n";
push(@hosts,$host);
}
}
# Get integer from user: either parameter or stdin
my $userinput;
if (defined $ARGV[0]) {
# user passed argument when running program
$userinput = $ARGV[0];
} else {
# prompt user for integer
$userinput = <STDIN>;
chomp ($userinput);
}
# Look up host and SSH into it
my $host = $hosts[$userinput];
if ( defined $host ) {
print "ssh: $host\n";
system("ssh", $host);
} else {
print "no host for $userinput\n";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment