-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmount_smb
executable file
·583 lines (486 loc) · 15.8 KB
/
mount_smb
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
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
#! /usr/bin/env bash
# On Mac OS X, mounts an SMB volume over an SSH tunnel. It uses autossh
# to insure the connection stays open, say, across sleeping a laptop.
# For more info, see the usage below.
###############################################################################
# Defaults with command-line overrides
# Initialize defaults from init file, if there is one:
[ -f $HOME/.mount_smb ] && source $HOME/.mount_smb
# Starting with macOS Sierra, users do not have permission to create
# directories in /Volumes/, so use /var/tmp/.
: ${mountprefix:="/var/tmp/${USER}-"}
# The host to which we connect to create the tunnel:
: ${sshhost:=}
# The workgroup:
: ${workgroup:=}
# The host with the SMB shares we want to mount:
: ${smbhost:=}
# The name of the SMB share you want to mount:
: ${share:=}
# Assume the local and remote users are the same:
: ${remoteuser:=$USER}
# The SSH config to use
: ${sshconfig:=$HOME/.ssh/config}
# The SSH identity to use
: ${sshid:=$HOME/.ssh/id_rsa}
# If non-null, do not open a Finder window post mount
: ${noopen:=}
# If non-null, be verbose
: ${verbose:=}
# If non-null, be debuggy
: ${debug:=}
# The place for the pidfile
: ${pidfileprefix:="/tmp/autosshpid"}
###############################################################################
set -eu
function errordie {
[ "${*-}" ] && echo "Error: $*" 1>&2
exit 1
}
function command_exists_p {
local v
v="$(type -p $1)" || errordie $1: command not found
echo $v
return 0
}
autossh="$(command_exists_p autossh)"
ssh="$(command_exists_p ssh)"
removepidfile="$(command_exists_p removepidfile)"
bindir=$(dirname "$autossh")"
function usage {
cat 1>&2 <<EOF
Usage: mount_smb [--verbose] [--debug]
[--user remote-user] [--no-finder-open]
[--sshconfig config]
[--sshidentity identity]
--sshhost sshhost --smbhost smbhost
--share name[,name2] --workgroup workgroup
On Mac OS X, mount an SMB share via an SSH tunnel. It uses autossh
to ensure the connection stays open, even in the face of sleeping a laptop
or interrupted network connections.
The script pauses in the middle to let you use the volume,
then when you continue it dismounts and shuts down the tunnel.
It uses "sudo" so you either need to supply the password or add to
/etc/sudoers for password-less operation.
Multiple instances of this script can run at a time, since each one
uses a new, local device and maps local ports 139 and 445 for that
device to the remote machine.
/etc/sudoers changes for password-less operation are below, which
should be added with the "visudo" command as root:
Defaults env_keep += "AUTOSSH_PIDFILE"
$USER ALL=(ALL) NOPASSWD: /sbin/ifconfig lo0 *
$USER ALL=(ALL) NOPASSWD: $bindir/autossh
$USER ALL=(ALL) NOPASSWD: $bindir/ssh
$USER ALL=(ALL) NOPASSWD: $removepidfile ${pidfileprefix}*
The above assumes that $bindir/ssh is used in preference to
/usr/bin/ssh. If that is not the case, then update which binary is allowed
by sudo.
This script has been tested on Mac OS X 10.9.
Optional arguments:
--verbose :: print informative messages, with date stamps
--debug :: aid in debugging; certain timeouts are smaller
--user remote-user :: defaults to \$USER
--no-finder-open :: do not open a Finder window, post mount
--sshconfig config :: defaults to \$HOME/.ssh/config
--sshidentity identity :: defaults to \$HOME/.ssh/id_dsa
Required arguments:
--sshhost sshhost :: the SSH host, or the other end of the tunnel
--smbhost smbhost :: the SMB host, which is accessible to the SSH host.
The SMB host can be different than the SSH host.
--workgroup workgroup :: the SMB workgroup
--share name[,name2,...] :: the SMB share to mount -- if multiple names
are given mount each one for the given smbhost
You can initialize the following command line arguments from
the script \$HOME/.mount_smb. The command line to variable name mapping
is:
--sshconfig sshconfig
--sshidentity sshidentity
--user remoteuser
--sshhost sshhost
--smbhost smbhost
--share share
--workgroup workgroup
--no-finder-open noopen
--verbose verbose
--debug debug
Optional BASH function hooks for \$HOME/.mount_smb:
mount_smb_usersetup
If defined, it is called before the autossh is initiated, so any
setup required for ssh to the remote host can be done, such as
knocking.
mount_smb_autossh_failed
If defined, it is called after autossh fails to establish a
connection to the remote host. It can be used, for example,
to forcibly knock.
mount_smb_timer
If defined, it is called every 10 minutes (every minute if --debug
is given) post-mount with these arguments:
mount_smb_timer \$minutes_since_mount
It can be used to open network access after a set period of time elapses,
for example.
mount_smb_post_mount
If defined, it is called post-mount, with arguments these arguments:
mount_smb_post_mount "\$mountpoint" "\$smbhost" "\$share"
It can be used to do post-mount things, like displaying a particular
share with the Finder. For example:
# When mounting share "john" on host "linuxhost", open the "incoming"
# subdirectory in the Finder.
function mount_smb_post_mount {
local mountpoint=\${1-}
local smbhost=\${2-}
local share=\${3-}
case "\$smbhost" in
linuxhost) [ "\$share" = "john" ] && open \$mountpoint/incoming ;;
esac
}
All of the above hooks are optional and are undefined unless defined by
the user.
EOF
exit 1
}
# errordie moved up, since it's needed there
function verbose {
# Use a brief date format
[ "$verbose" ] && echo "$(date "+%Y-%m-%d %H:%M:%S"): $@"
return 0
}
function debug {
# Use a brief date format
[ "$debug" ] && echo "$(date "+%Y-%m-%d %H:%M:%S"): $@"
# Set the return value for this function
return 0
}
while test $# -gt 0; do
case $1 in
--debug) debug=$1 ;;
--verbose) verbose=$1 ;;
# deprecated, but still works:
--folder) share=$2; shift ;;
--share) share=$2; shift ;;
--help) usage ;;
--no-finder-open) noopen=$1 ;;
--smbhost) smbhost=$2; shift ;;
--sshconfig) sshconfig=$2; shift ;;
--sshidentity) sshid=$2; shift ;;
--sshhost) sshhost=$2; shift ;;
--user) remoteuser=$2; shift ;;
--workgroup) workgroup=$2; shift ;;
-*) usage ;;
*) usage ;;
esac
shift
done
[ "$sshhost" ] || errordie sshhost is not set, use --sshhost
[ "$smbhost" ] || errordie smbhost is not set, use --smbhost
[ "$share" ] || errordie share is not set, use --share
[ "$workgroup" ] || errordie workgroup is not set, use --workgroup
shares="$(echo $share | sed 's/,/ /g')"
# Leave here for debugging (remove `:' prefix to have it executed):
: cat <<EOF
Parameters:
sshhost=$sshhost
workgroup=$workgroup
smbhost=$smbhost
remoteuser=$remoteuser
sshconfig=$sshconfig
sshid=$sshid
share=$share
shares=$shares
EOF
###############################################################################
function find_device {
# Find the first unused lo0 IP address.
local max=$(/sbin/ifconfig lo0 | \
grep "inet " \
| sed -e 's/.*inet 127\.0\.0\.//g' \
-e 's/ netmask.*//g' | \
sort -n | tail -1)
echo 127.0.0.$(( $max + 1 ))
}
function read_encoded_password {
local pass
[ "${EMACS-}" ] || stty -echo
read -p "Password:" -s pass
[ "${EMACS-}" ] || stty echo
python -c "import sys, urllib as ul; print ul.quote(\"$pass\")"
}
function set_password {
echo "Enter your password for the SMB shares on $smbhost:"
password="$(read_encoded_password)"
printf '\n'
}
function device_up {
verbose binding $device
sudo $ifconfig lo0 ${device} alias up
}
function device_down {
verbose unbinding $device
if ! sudo $ifconfig lo0 ${device} -alias down; then
echo $ifconfig -alias down failed
fi
}
function start_tunnel {
local n=5
device_up
# Using -o ControlPersist=yes causes the autossh to not stick around,
# which is definitely not what we want, because the reconnect will not
# happen across sleeping the OS. However, not using it also causes
# the autossh to stick around too long, after the ``-O exit'' is sent.
# I'd rather autossh's accumulate in the background than the reconnect
# not happen.
#
# To work around the above problem, we use AUTOSSH_PIDFILE and kill
# it manually when the script exits.
#
# TODO: consider setting AUTOSSH_POLL=60 (600 is the default) so
# so the ssh will come back quicker.
if ! sudo AUTOSSH_PIDFILE=$pidfile $autossh -M 0 \
-L ${device}:139:${smbhost}:139 \
-L ${device}:445:${smbhost}:445 \
-F $sshconfig -i $sshid \
-o ControlMaster=yes \
-o ControlPath=$socket \
-o ServerAliveInterval=10 \
-o ServerAliveCountMax=3 \
-o StrictHostKeyChecking=no \
-N -f \
$USER@$sshhost
then
verbose autossh failed
device_down
return 1
fi
trap stop_tunnel_and_cleanup 0
# Take a chance that waiting will cause the tunnel to appear.
n=3
while [ $n -gt 0 ]; do
if [ -e $socket ]; then
break
else
verbose waiting for tunnel to initialize on ${device}...
sleep 5
fi
n=$(( $n - 1 ))
done
if [ ! -e $socket ]; then
verbose autossh did not create $socket file
device_down
if [ "$(type -t mount_smb_autossh_failed)" = "function" ]; then
if ! mount_smb_autossh_failed; then
verbose NOTE: mount_smb_autossh_failed failed
fi
fi
return 1
else
return 0
fi
}
function start_tunnel_retry {
[ "${1-}" ] || usage start_tunnel_retry should be given a count
local n=$1
local status
while [ $n -gt 0 ]; do
verbose starting tunnel
if ! start_tunnel; then
verbose tunnel did not start, try again
n=$(( $n - 1 ))
status=1
else
status=0
# Our work here is done:
break
fi
done
return $status
}
function stop_tunnel_and_cleanup {
verbose exiting from trap, stop_tunnel_and_cleanup
for mountpoint in $mountpoints; do
# can't test the directory's existence the standard way because
# this will cause the script to hang. Use the `mount' command.
if mountedp $mountpoint; then
verbose $mountpoint is mounted
if umount $mountpoint; then
verbose $mountpoint unmounted
else
errordie umount $mountpoint failed
fi
else
verbose $mountpoint is not mounted
fi
# Give the volume time to unmount
sleep 2
done
if ! sudo $ifconfig lo0 ${device} -alias down; then
verbose NOTE: failed to remove $device
fi
# do this last (so no need to error protect it)
if [ -e $socket ]; then
sshargs="$USER@$sshhost -F $sshconfig -i $sshid -S $socket "
verbose shutting down ssh...
sudo $ssh $sshargs -O exit
verbose killing autossh...
sudo $removepidfile $pidfile
else
verbose socket does not exist, cannot shutdown ssh
# get rid of the pidfile, at least
sudo $removepidfile $pidfile
fi
}
function mount_shares {
local mountpoint
set_password
for share in $shares; do
mountpoint="${mountprefix}$smbhost-$share"
mountpoints="$mountpoints $mountpoint"
mkdir -p $mountpoint
while ! /sbin/mount -t smbfs \
"//${workgroup};${remoteuser}:${password}@${device}/${share}" \
$mountpoint
do
# Assume it failed because the password was incorrect, so
# ask again
set_password
done
# If a function named "mount_smb_post_mount" was defined in
# $HOME/.mount_smb (or possibly in $HOME/.bashrc), then call it.
# It can be used to do post-mount things, like displaying a particular
# share with the Finder.
if [ "$(type -t mount_smb_post_mount)" = "function" ]; then
if ! mount_smb_post_mount "$mountpoint" "$smbhost" "$share"; then
verbose NOTE: mount_smb_post_mount failed
fi
elif [ "$noopen" ]; then
: # do nothing
else
# Open a Finder on it
open $mountpoint
fi
done
announce
}
function check_shares {
local mountpoint
local share
debug check_shares...
for mountpoint in $mountpoints; do
if mountedp $mountpoint; then
debug $mountpoint is mounted
continue
fi
verbose $mountpoint is no longer mounted
# Let's try and bring it back...
# (We assume that the password originally given is still good.)
# extract $share from $mountpoint
share=$(echo $mountpoint | sed "s,${mountprefix}.*-\\(.*\\)\$,\\1,")
mkdir -p $mountpoint
if /sbin/mount_smbfs \
"//${workgroup};${remoteuser}:${password}@${device}/${share}" \
$mountpoint
then
verbose successfully remounted $mountpoint
else
errordie Could not remount $mountpoint
fi
done
}
function announce {
cat <<EOF
When you are done with the share, press ENTER and it will be unmounted
EOF
}
# Increment the minute timer and possibly call the mount_smb_timer function
# defined by the user, which might do something like knock.
min=1
function incf_min {
min=$(( $min + ${1-1} ))
if [ "$(type -t mount_smb_timer)" = "function" ]; then
if ! mount_smb_timer $min; then
verbose "NOTE: mount_smb_timer failed [1]"
fi
fi
}
function mountedp {
# return 0 if $1 is mounted, 1 otherwise
if mount | grep -q " on .*$1 "; then
return 0
else
return 1
fi
}
###############################################################################
# We put the main body of code in a list {} so that if the script is
# modified after it starts it won't cause problems.
{
if [ "$(type -t mount_smb_usersetup)" = "function" ]; then
if ! mount_smb_usersetup; then
verbose NOTE: mount_smb_usersetup failed
fi
fi
# This file is removed by ssh once the control socket is shutdown
# or the connection to the remote host is lost.
socket=/tmp/smbtunnel$$
pidfile=${pidfileprefix}$$
password=
mountpoints=
ifconfig=/sbin/ifconfig
if device=$(find_device); then
if [ ! "$device" ]; then
errordie Could not find device
fi
else
errordie Could not find device
fi
start_tunnel_retry 3
mount_shares
# Set timeout (in seconds) for our periodic checks.
if [ "$debug" ]; then
timeout=60
debug timeout=$timeout
else
timeout=600
fi
while true; do
# wake up every once in a while to see if $socket exists
if read -t $timeout foo; then
debug User typed something...
break
else
incf_min $(( timeout / 60 ))
if [ "$(type -t mount_smb_timer)" = "function" ]; then
debug Calling mount_smb_timer $min...
if ! mount_smb_timer "$min"; then
verbose "NOTE: mount_smb_timer failed [2]"
fi
fi
# If the socket disappears that means the ssh that autossh
# started died, due to a network outage or something similar.
# Wait for it to come back.
# NOTE: if the firewall is rebooted then we may need to
# knock sooner than we think. In this case, the
# autossh-created file ($socket) will not reappear until
# we knock again. I don't see a way around this, unless
# we want to try and knock after some period of time.
# Maybe we could ping the host to see if it's down, then
# up, and set a flag that we'll need to reknock?
ok_now=
while [ ! -e "$socket" ]; do
verbose waiting for $socket to reappear...
sleep 60
incf_min 1
ok_now=xxx
done
if [ "$ok_now" ]; then
verbose socket reappeared, all systems go
announce
fi
# Check that the volumes are still mounted; try to remount
# if they are not. Why they become unmounted is a mystery.
# even when the tunnel is working, they sometimes just
# get dismounted.
check_shares
fi
done
# all cleanup is done in the trap handler
exit
}