Tag: cifs

  • Garbage Sysadmin: Easily Make CIFS Mounts

    Garbage Sysadmin: Easily Make CIFS Mounts

    I’ve been rebuilding my Raspberry Pi collection from scratch, and moving from Ubuntu Server to Debian/Raspbian Bookworm. One of the tasks that I quickly tried to automate was reconnecting my CIFS mounts. I wanted to do it better, and came across this method, with the help of ChatGPT, to mount them at boot:

    #!/bin/bash
    
    # Check if the script is run as root
    if [[ $EUID -ne 0 ]]; then
       echo "This script must be run as root"
       exit 1
    fi
    
    # Check for correct number of arguments
    if [ "$#" -ne 4 ]; then
        echo "Usage: $0 <RemoteDirectory> <MountDirectory> <Username> <Password>"
        exit 1
    fi
    
    REMOTE_DIR="$1"
    MOUNT_DIR="$2"
    USERNAME="$3"
    PASSWORD="$4"
    CREDENTIALS_PATH="/etc/samba/credentials-$(basename "$MOUNT_DIR")"
    
    # Escape the mount directory for systemd
    UNIT_NAME=$(systemd-escape -p --suffix=mount "$MOUNT_DIR")
    
    # Create mount directory
    mkdir -p "$MOUNT_DIR"
    
    # Create credentials file
    touch "$CREDENTIALS_PATH"
    echo "username=$USERNAME" > "$CREDENTIALS_PATH"
    echo "password=$PASSWORD" >> "$CREDENTIALS_PATH"
    chmod 600 "$CREDENTIALS_PATH"
    
    # Create systemd unit file
    UNIT_FILE_PATH="/etc/systemd/system/$UNIT_NAME"
    echo "[Unit]
    Description=Mount Share at $MOUNT_DIR
    After=network-online.target
    Wants=network-online.target
    
    [Mount]
    What=$REMOTE_DIR
    Where=$MOUNT_DIR
    Type=cifs
    Options=_netdev,iocharset=utf8,file_mode=0777,dir_mode=0777,credentials=$CREDENTIALS_PATH
    TimeoutSec=30
    
    [Install]
    WantedBy=multi-user.target" > "$UNIT_FILE_PATH"
    
    # Reload systemd, enable and start the unit
    systemctl daemon-reload
    systemctl enable "$UNIT_NAME"
    systemctl start "$UNIT_NAME"
    
    echo "Mount setup complete. Mounted $REMOTE_DIR at $MOUNT_DIR"Code language: Bash (bash)

    I’m sure this is totally insecure and a terrible idea, but it works for me so back off, buddy!

    Please don’t follow me as an example of what to do, but take this code for anything you need.