make getpeername() return the original socket address which before it was intercepted
[hband-tools.git] / user-tools / ssh-agent-finder
blobe3633113faae9ad967d054439e071f318a25a50e
1 #!/bin/bash
3 true <<EOF
4 =pod
6 =head1 NAME
8 ssh-agent-finder - Find a working ssh agent on the system so you get the same in each of your logon sessions
10 =head1 USAGE EXAMPLE
12 . ssh-agent-finder -Iva
14 =cut
16 EOF
19 interactive=1
20 must_have_keys=1
21 list_all_sockets=''
22 verbose=''
23 sourced=''
25 . /usr/lib/tool/bash-utils
27 parse_opts()
29 local OPTIND=1
30 Usage="Usage: $0 [-IkKav]
31 -I No interactive, use first socket
32 -k Use socket having keys (default)
33 -K Use socket not necessary having keys
34 -a List all sockets
35 -v Verbose"
36 if [ ."$1" = .--help ]
37 then
38 echo "$Usage" >&2
39 return 1
41 while getopts hIkKav opt "$@"
43 case "$opt" in
44 h) echo "$Usage" >&2
45 return 1;;
46 I) interactive='';;
47 k) must_have_keys=1;;
48 K) must_have_keys='';;
49 a) list_all_sockets=1;;
50 v) verbose=1;;
51 '?') return 1;;
52 esac
53 done
54 return 0
57 if [ $must_have_keys ]
58 then
59 might_have_keys_or_not=''
60 else
61 might_have_keys_or_not=1
62 fi
66 if [ "$0" != "$BASH_SOURCE" ]
67 then
68 sourced=1
72 parse_opts "$@"
73 code=$?
74 if [ $code != 0 ]
75 then
76 if [ $sourced ]
77 then
78 return $code
79 else
80 exit $code
85 for file in /tmp/ssh-*/agent.* $HOME/.gnupg/S.gpg-agent.ssh $HOME/.cache/keyring-*/ssh
87 if [ -S "$file" ]
88 then
89 SSH_AUTH_SOCK=$file capture2 ssh-add -l
90 code=$?
91 if [ $code = 0 ]
92 then
93 live_socket=1
94 has_keys=1
95 use=1
96 elif [ $code = 1 ]
97 then
98 live_socket=1
99 has_keys=''
100 if [ $must_have_keys ]
101 then
102 use=''
103 else
104 use=1
106 else
107 # code == 2: non-functioning socket
108 live_socket=0
109 has_keys=''
110 use=''
113 if [[ ( ( $might_have_keys_or_not || $has_keys ) && ( $interactive || $verbose ) ) || $list_all_sockets ]]
114 then
115 echo =============
116 if [ "$SSH_AUTH_SOCK" = "$file" ]
117 then
118 echo -n "(current) *** "
120 echo "SSH_AUTH_SOCK $file"
121 [ -n "$capture2_stdout" ] && echo "$capture2_stdout"
122 [ -n "$capture2_stderr" ] && echo "$capture2_stderr" >&2
125 if [[ $live_socket && ( ( $might_have_keys_or_not || $has_keys ) || $list_all_sockets ) ]]
126 then
127 if [ $interactive ]
128 then
129 use=''
130 [[ $might_have_keys_or_not || $has_keys ]] && default=Y || default=N
131 read -e -p "Use this socket? [$default] "
132 [ -n "$REPLY" ] || REPLY=$default
133 REPLY=${REPLY^^}
134 REPLY=${REPLY:0:1}
135 [ "$REPLY" = Y ] && use=1
137 if [ $use ]
138 then
139 if [ $sourced ]
140 then
141 export SSH_AUTH_SOCK=$file
142 return 0
143 else
144 echo "export SSH_AUTH_SOCK='${file//\'/\'\\\'\'}'"
145 exit 0
147 break
151 done
153 false