-
Notifications
You must be signed in to change notification settings - Fork 0
/
ssh_autocomp.bash
284 lines (236 loc) · 8.38 KB
/
ssh_autocomp.bash
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
# Space-separated list of paths to search for HOST directives:
SSH_CONFIG_PATHS=~/.ssh/config
# Maximum number of ControlMaster connections to open:
MAX_CM_OPEN=3
# To enable debugging, run `touch debug.log`.
# If there are more than MAX_CM_OPEN connections possible, use this heuristic to select the servers to connect to:
HEURISTIC="most" # "" "last" "most"
HEURISTIC_CACHE_LNC=~/.ssh_last_n
HEURISTIC_CACHE_MC=~/.ssh_most
#
# UTILITY FUNCTIONS
#
dbgecho() {
# Comment these out to disable printing debug messages:
[ -f "./debug.log" ] && echo "$@" >> "debug.log"
}
# Compatibility mode:
OUTPUT_WITHOUT_ATPREFIX=false
if [[ "$BASH_VERSION" == 3.2.* ]]; then
OUTPUT_WITHOUT_ATPREFIX=true
dbgecho "DETECTED BASH 3.2.X; USING OUTPUT_WITHOUT_ATPREFIX"
fi
#
# UTILITY FUNCTIONS
#
function firstcmd() {
for ALTERNATIVE in "$@"; do
if command -v "$ALTERNATIVE" 1>/dev/null 2>&1; then
echo -n "$ALTERNATIVE"
return
fi
done
dbgecho "No Alternatives Found: $@"
}
# Binaries; automatically use the first binary that exists
BIN_STAT=$(firstcmd gstat stat)
BIN_SED=$(firstcmd gsed sed)
BIN_DATE=$(firstcmd gdate date)
dbgecho "SELECTED $BIN_STAT FOR stat"
dbgecho "SELECTED $BIN_SED FOR sed"
dbgecho "SELECTED $BIN_DATE FOR date"
# Global state:
OPEN_CONN=() # Connections to open
HOSTS=() # All possible hosts
# Check if the passed cache file is out-of-date:
function __maybe_make_cache() {
local CACHE_FILE
CACHE_FILE="$1"
local TS_CACHE TS_CONFIG CFG TS_CFG
[ -f "$CACHE_FILE" ] || return 0
TS_CACHE=$($BIN_STAT -c %Y "$CACHE_FILE")
TS_CONFIG=$($BIN_DATE -d "-1 day" +%s) # One day ago; this way we renew the cache daily
for CFG in $SSH_CONFIG_PATHS; do
TS_CFG=$($BIN_STAT -c %Y $CFG)
(( $TS_CFG > $TS_CONFIG )) && TS_CONFIG=$TS_CFG
done
test $TS_CONFIG -gt $TS_CACHE
return $?
}
# Given a heuristic file and candidates, select the $MAX_CM_OPEN highest-ranked connections to open:
function __select_conn() {
local HEURISTIC_FILE CANDIDATES
HEURISTIC_FILE="$1"
shift
CANDIDATES=( "$@" )
local LNC TARGET
# Read in the cache
# Store in $OPEN_CONN the first $MAX_CM_OPEN lines of $HEURISTIC_FILE that appear in $CANDIDATES
OPEN_CONN=()
while read LNC || [[ -n "$LNC" ]]; do
for TARGET in ${CANDIDATES[@]}; do
if [ ! -z "$TARGET" ] && [ "$LNC" = "$TARGET" ]; then
dbgecho "SELECT CONN: $TARGET"
OPEN_CONN+=( "$TARGET" )
CANDIDATES=( "${CANDIDATES[@]/$TARGET}" )
break
fi
done
if [ "${#OPEN_CONN[@]}" -ge "$MAX_CM_OPEN" ]; then
break
fi
done < "$HEURISTIC_FILE"
}
# Acquire a lock on the heuristic file; if successful, update the heuristic file the output of an arbitrary function
function __lock_update() {
local HEURISTIC_FILE INNER_FUNC
HEURISTIC_FILE="$1"
INNER_FUNC="$2"
HEURISTIC_FILE_LOCK="$HEURISTIC_FILE.lock"
dbgecho "UPDATE FILE $HEURISTIC_FILE"
(
if flock -n 199; then
# Call the inner function and write output to cache:
$INNER_FUNC > "$HEURISTIC_FILE"
rm "$HEURISTIC_FILE_LOCK"
dbgecho "SUCCESFULLY UPDATED"
else
dbgecho "CANNOT ACQUIRE CACHE LOCK"
fi
) 199>"$HEURISTIC_FILE_LOCK"
}
#
# HEURISTICS
#
function __heuristic_mc() {
local CANDIDATES
CANDIDATES=( ${HOSTS[@]} )
local CANDIDATE_LIST=$(printf "|%s" "${CANDIDATES[@]}")
CANDIDATE_LIST="${CANDIDATE_LIST#|}"
local REGEX_REPLACE="s/^.*(${CANDIDATE_LIST}).*$/\1/"
local REGEX_STRIPNUM="s/^[ ]*[0-9]+ (.*)$/\1/"
local FREQLINES=( $(fc -rl -3000 | grep '^[^a-zA-Z]*ssh' | "$BIN_SED" -re "$REGEX_REPLACE" | sort | uniq -c | sort -nr | "$BIN_SED" -re "$REGEX_STRIPNUM") )
dbgecho "MC CANDIDATES: ${FREQLINES[@]}"
for LINE in ${FREQLINES[@]}; do
for HOST in ${CANDIDATES[@]}; do
if [ ! -z "$HOST" ] && [ "$LINE" = "$HOST" ]; then
CANDIDATES=( "${CANDIDATES[@]/$HOST}" )
dbgecho " MC: $HOST"
echo $HOST
break
fi
done
if [ "${#CANDIDATES[@]}" = 0 ]; then
break
fi
done
}
function __heuristic_lnc() {
local CANDIDATES
CANDIDATES="${HOSTS[@]}"
for LINE in $(fc -rl -3000 | grep '^[^a-zA-Z]*ssh'); do
for HOST in "${CANDIDATES[@]}"; do
if [ ! -z "$HOST" ] && [[ $LINE == *$HOST* ]]; then
CANDIDATES=("${CANDIDATES[@]/$HOST}")
dbgecho " LNC: $HOST"
echo $HOST
break
fi
done
if [ "${#CANDIDATES[@]}" = 0 ]; then
break
fi
done
}
#
# MAIN
#
# Actually open the connection:
function __open_conn() {
local SRVSTR CMPATH
SRVSTR="$2@$1"
SRVSTR="${SRVSTR#@}" # Remove leading connection if it exists
# Check if controlmaster is supported
CMSUPPORT=$(ssh -G $SRVSTR | grep '^controlmaster ')
CMSUPPORT=${CMSUPPORT#controlmaster } # Remove leading controlmaster
if [ -z "$CMSUPPORT" ] || [ "$CMSUPPORT" == "false" ]; then
dbgecho "CONTROLMASTER DISABLED FOR $SRVSTR!"
return 255
fi
# Get controlmaster path
CMPATH=$(ssh -G $SRVSTR | grep '^controlpath ')
CMPATH=${CMPATH#controlpath } # Remove leading controlpath
if [ -S $CMPATH ]; then
# If it is a socket, check to see if it is connected
# Note that the $SRVSTR argument is just filler.
if ssh -S "$CMPATH" -O check "$SRVSTR" >/dev/null 2>&1 ; then
dbgecho "CONTROLMASTER FOR $SRVSTR ALREADY OPEN!"
return 0
fi
fi
dbgecho "OPEN CONTROLMASTER CONNECTION TO $SRVSTR"
# Start an SSH (-M) master connection, (-N) do not execute anything, (-n) do not read anything from stdin, (-f) go to background, (-oBatchMode) fail rather than ask for a password
( ssh -MNnf -oChallengeResponseAuthentication=no -oPasswordAuthentication=no -oBatchMode=yes "$SRVSTR" >/dev/null 2>&1 & )
}
function _ssh() {
dbgecho ""
dbgecho "*********************"
dbgecho "${COMP_WORDS[COMP_CWORD]}"
local LAST_WORD LAST_SERVER LAST_USER
LAST_WORD="${COMP_WORDS[COMP_CWORD]}"
LAST_SERVER="${LAST_WORD#*@}"
# Check if a username is specified:
case "${LAST_WORD%$LAST_SERVER}" in
*@) LAST_USER="${LAST_WORD%@$LAST_SERVER}";; # If the string is <user>@<servername>, keep the <user>
*) LAST_USER="";; # Otherwise, we don't know <user>
esac
HOSTS=$(grep -i '^Host' $SSH_CONFIG_PATHS 2>/dev/null | grep -v '[?*]' | cut -d ' ' -f 2-)
local TARGETS
TARGETS=( $(compgen -W "$HOSTS" -- $LAST_SERVER) )
if [ "${#TARGETS[@]}" = 0 ]; then
dbgecho "NO TARGETS FOUND"
return 127
fi
dbgecho "TARGETS ${#TARGETS[@]}: ${TARGETS[@]/#/-> }"
# If the username is defined, add that to the front of each suggested server:
COMPREPLY=()
if [ -z "$LAST_USER" ]; then
COMPREPLY=( "${TARGETS[@]}" )
else
if [ $OUTPUT_WITHOUT_ATPREFIX = true ]; then
COMPREPLY=( "${TARGETS[@]/#/@}" )
else
COMPREPLY=( "${TARGETS[@]/#/$LAST_USER@}" )
fi
fi
dbgecho "COMPREPLY ${#COMPREPLY[@]}: ${COMPREPLY[@]/#/-> }"
# Now COMPREPLY contains the list of matching hosts.
if [ "${#TARGETS[@]}" -gt $MAX_CM_OPEN ]; then
dbgecho "TOO MANY TARGETS; USING HEURISTIC TO SELECT $MAX_CM_OPEN"
if [ "$HEURISTIC" = "last" ]; then
if __maybe_make_cache "$HEURISTIC_CACHE_LNC"; then
__lock_update "$HEURISTIC_CACHE_LNC" __heuristic_lnc
fi
# Update OPEN_CONN using the LNC heuristic:
__select_conn "$HEURISTIC_CACHE_LNC" ${TARGETS[@]}
elif [ "$HEURISTIC" = "most" ]; then
if __maybe_make_cache "$HEURISTIC_CACHE_MC"; then
__lock_update "$HEURISTIC_CACHE_MC" __heuristic_mc
fi
# Update OPEN_CONN using the MC heuristic:
__select_conn "$HEURISTIC_CACHE_MC" ${TARGETS[@]}
else
dbgecho "NO HEURISTIC; ABANDONING ATTEMPT"
return 128
fi
else
# Open all connections:
OPEN_CONN=( ${TARGETS[@]} )
fi
dbgecho "OPEN_CONN: ${OPEN_CONN[@]}"
for TARGET in "${OPEN_CONN[@]}"; do
__open_conn "$TARGET" "$LAST_USER"
done
return 0
}
complete -F _ssh ssh