This repository has no description
1.5 kB
48 lines
1#!/usr/bin/env bash
2# Pick one of your live forwarded SSH agents and print an export line.
3# Usage: eval "$(ssh-agent-pick)"
4
5uid=$(id -u)
6cands=()
7labels=()
8
9# newest first: sshd creates the socket when the connection is established
10while IFS= read -r -d '' line; do
11 sock=${line#* }
12 [ -S "$sock" ] || continue
13 [ "$(stat -c %u "$sock")" = "$uid" ] || continue
14 rc=0
15 keys=$(SSH_AUTH_SOCK=$sock ssh-add -l 2>/dev/null) || rc=$?
16 [ "$rc" -le 1 ] || continue # 2 = cannot connect (stale)
17 if [ "$rc" -eq 1 ]; then
18 keys="(no identities)"
19 else
20 keys=$(printf '%s\n' "$keys" | awk '{ $1 = $2 = ""; $NF = ""; sub(/^ +/, ""); sub(/ +$/, ""); print }' | paste -sd, -)
21 fi
22 since=$(date -d "@${line%% *}" '+%F %T')
23 cands+=("$sock")
24 labels+=("$since $keys $sock")
25done < <(find /tmp/ssh-* "$HOME/.ssh/agent" -maxdepth 1 -type s \( -name 'agent.*' -o -name '*.sshd.*' \) \
26 -printf '%T@ %p\0' 2>/dev/null | sort -zrn)
27
28if [ ${#cands[@]} -eq 0 ]; then
29 echo "ssh-agent-pick: no live forwarded agent found" >&2
30 exit 1
31fi
32
33if [ ${#cands[@]} -eq 1 ]; then
34 choice=${cands[0]}
35elif [ -t 2 ]; then
36 sel=$(printf '%s\n' "${labels[@]}" | fzf --height=~10 --reverse --prompt='agent> ') || exit 1
37 choice=${sel##* }
38else
39 PS3='agent> '
40 select _ in "${labels[@]}"; do
41 [ -n "${REPLY:-}" ] && [ "$REPLY" -ge 1 ] 2>/dev/null && [ "$REPLY" -le ${#cands[@]} ] || continue
42 choice=${cands[REPLY - 1]}
43 break
44 done
45fi
46
47[ -n "${choice:-}" ] || exit 1
48printf "export SSH_AUTH_SOCK='%s'\n" "$choice"