aboutsummaryrefslogtreecommitdiff
path: root/ssf
blob: 2366b29c6edf5f4dcea793f9fb79ce0c1d5ec7a6 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
#!/usr/bin/env perl
#
# Author: Guillermo Ramos <gramos@gramos.me>
# SPDX-License-Identifier: BSD-3-Clause
#
# Minimalistic SSH connector which uses FZF, the SSH config and the known_hosts file
# to show a reasonable list of machines to connect to. Then it starts or attaches to
# a remote tmux session named as the current user.
#
################################################################################

use strict;
use warnings;

my @hosts;
my %aliases;

my $remote_user = $ENV{SSF_REMOTE_USER} || $ENV{USER};

open(my $ssh_config, '<', "$ENV{HOME}/.ssh/config") or die "nope";
while (my $line = <$ssh_config>) {
    if ($line =~ /^Host ([^#\n]+)(?: # (.*))?$/) {
        push @hosts, split(/ /, $1);
        if (defined $2) {
            $aliases{$_} = $1 foreach split / /, $2;
        }
    }
}

my $egrep_regex = join "|", grep { $_ =~ /\*/ } @hosts;
$egrep_regex =~ s/\./\\./g;
$egrep_regex =~ s/\*/.*/g;

my $known_hosts = `
    grep -E '$egrep_regex' ~/.ssh/known_hosts |
    cut -f1 -d" " |
    sort -u
`;
my $hosts_no_wild = join "\n", grep { not $_ =~ /\*/ } @hosts;
my $aliases = join "\n", keys %aliases;
my $prompt = @ARGV ? "@ARGV " : "";
my $selection = `
    echo -n "${known_hosts}$aliases\n$hosts_no_wild" |
    fzf -1 --print-query -q "$prompt"
`;
my $retval = $? >> 8;
my @lines = split "\n", $selection;

my $hostname;
if ($retval == 0) {
    $hostname = $lines[1];
} elsif ($retval == 1) {
    $hostname = $lines[0];
} else {
    exit $retval;
}

$hostname =~ s/^\s+|\s+$//g; # Trim whitespace
my $host = $aliases{$hostname} || $hostname; # Resolve alias

# Save the final command to the shell history...?
#`print -s "ssh $host"`;

# Special behavior for tmux
if (exists $ENV{TMUX}) {
    my $window_id = `tmux list-windows -F '#{window_index}' -f '#{==:#{window_name},$hostname}'`;
    $window_id =~ s/^\s+|\s+$//g; # Trim whitespace
    if ($window_id ne '') {
        # The window exists; select it instead
        `tmux select-window -t $window_id`;
    } else {
        # The window does not exist; make the connection in the current one
        # and it to the machine we're connecting to
        `tmux rename-window $hostname`;
        system 'ssh', '-t', $host, "sh -c \"tmux new -As $remote_user\"";
        `tmux rename-window '!$hostname'`;
    }
} else {
    exec 'ssh', '-t', $host, "sh -c \"tmux new -As $remote_user\"";
}