Linux – How to mount a smb drive with different credentials (user name and password) on Linux

autofslinuxmountsmbfs

Ok, I have here a laptop on which runs Linux (CentOS 7). The laptop will be used from different user's (which have all different login's on the laptop). We have in our network a Samba server. All users which have a login on the laptop have also different login's (user name and password) for different smb drives. The question is now how to configure the linux laptop so that the smb drives for each user will be mount automatically?

The default tipps and hints like adding following line to the fstab

//servername/sharename  /media/windowsshare  cifs   uid=ubuntuuser,credentials=/home/ubuntuuser/.smbcredentials,iocharset=utf8,sec=ntlm   0       0

and create the credentials file (/home/ubuntuuser/.smbcredentials) don't works in my case because the credential file is for each user the same (but should be a different). Also specifying the credential file like ~/.smbcredentials don't works because the home directory ~/ is unknown at mount time …

Best Answer

Found it.

Source is: http://wiki.centos.org/TipsAndTricks/WindowsShares at point "5. Yet Another Even-better method"

The trick is to use autofs:

  1. Add this line to /etc/auto.master:

    /mnt/smb /etc/auto.smb.top
    
  2. Create /etc/auto.smb.top as:

    * -fstype=autofs,-Dhost=& file:/etc/auto.smb.sub
    
  3. Create /etc/auto.smb.sub as (adjust as needed):

    * -fstype=cifs,credentials=/root/secret.txt,uid=500,gid=100 ://${host}/&
    

    And here I can specify also the home directory with ${HOME} like

    * -fstype=cifs,credentials=${HOME}/secret.txt,uid=500,gid=100 ://${host}/&
    

    so that each user has his own credentials file :-)

  4. Let's make sure that the permission bits are correct and restart the service:

    [root@host]# chmod 644 /etc/auto.smb.*
    [root@host]# /sbin/service autofs restart
    
  5. Now you can access by simply typing:

    [user@host]$ cd /mnt/smb/winbox/getme