Linux autofs: Authenticate against different SMB servers

I work with lots of Windows machines on different Windows Domains.  I try to make use the the autofs to automagically mount them.  Herein lies an issue.  The domains require different credentials to access them.  The stock Fedora auto.smb does not have a way to provide credentials to the server.  I have modified mine as shown below to add the ability to provide credentials based on the name of the server you are trying to access:

#!/bin/bash

# This file must be executable to work! chmod 755!

key="$1"
if [ -r /etc/smb.credentials.$1 ]
then
 CREDENTIALS=/etc/smb.credentials.$1
else
 CREDENTIALS=/etc/smb.credentials
fi

opts="-fstype=cifs,credentials=$CREDENTIALS"

for P in /bin /sbin /usr/bin /usr/sbin
do
 if [ -x $P/smbclient ]
 then
 SMBCLIENT=$P/smbclient
 break
 fi
done

[ -x $SMBCLIENT ] || exit 1
$SMBCLIENT -gNL $key --authentication-file=$CREDENTIALS 2>/dev/null | awk -v key="$key" -v opts="$opts" -F'|' -- '
 BEGIN   { ORS=""; first=1 }
 /Disk/  {
 if (first)
 print opts; first=0
 dir = $2
 loc = $2
 # Enclose mount dir and location in quotes
 # Double quote "$" in location as it is special
 gsub(/\$$/, "\\$", loc);
 print " \\\n\t \"/" dir "\"", "\"://" key "/" loc "\""
 }
 END     { if (!first) print "\n"; else exit 1 }
 '

So, to access a server, I can create a /etc/smb.credentials.{servername} with appropriate username/passwords in it.  If there is more than one server in the same domain, I just use symlinks between the two files.  I guess it would be slicker if I did something like /smb/{DOMAIN}/{SERVER}/{SHARES}, but at this time, I have what I need.

Leave a Reply