Automounting smb network drives with systemd

 · 1 min · torgeir

Terminal Linux Systemd Smb Cifs Mount

You can automount filesystems on demand with systemd.

sudo su
mkdir -p /mnt/fileserver/torgeir

Add a file /etc/systemd/system/mnt-fileserver-torgeir.automount with the name of the folder you plan to mount it to, under /mnt/. This will make the filesystem automaticaly mount on demand.

cat <<EOF > /etc/systemd/system/mnt-fileserver-torgeir.automount
[Unit]
Description=Mount Share at boot

[Automount]
Where=/mnt/fileserver/torgeir

[Install]
WantedBy=multi-user.target
EOF

Add a corresponding /etc/systemd/system/mnt-fileserver-torgeir.mount that specifies what to mount, and how.

cat <<EOF > /etc/systemd/system/mnt-fileserver-torgeir.mount
[Unit]
Description=Mount cam share at boot

[Mount]
What=//fileserver/torgeir
Where=/mnt/fileserver/torgeir
Options=_netdev,uid=1000,credentials=/home/torgeir/.credentials,iocharset=utf8,rw,vers=3.0
Type=cifs
TimeoutSec=2

[Install]
WantedBy=multi-user.target
EOF

Take note of the uid and credentials that specify the permissions to use for files in the folder and how to authenticate towards //fileserver, which in this case in running samba. The mountpoint Where must match the name of the automount unit to make this work automatically. I.e. the filename /etc/systemd/system/mnt-fileserver-torgeir.mount matches the folder structure Where=/mnt/fileserver/torgeir.

Create the file to hold credentials and put your samba username and password in it

cat <<EOF > ~/.credentials
username=<username>
password=<password>
EOF

Make it accessible only by your user

chmod u=rw,go-rwx ~/.credentials

Make systemctl discover the unit files

systemctl daemon-reload

Enable and start the automount unit

systemctl enable --now mnt-fileserver-torgeir.automount
journalctl -xe

Now make use of the folder

cd /mnt/fileserver/torgeir
ls

And watch it mount!