How to automatically mount remote directories on login / startup

18,365

Indeed, .bashrc isn't right. That file is read when you open a terminal running an interactive shell (if your shell is bash).

You can perform sshfs mounts at boot time, but that only works if you don't need any interactive authentication: in most setups this means a passwordless key. (There are other ways, but they only apply inside trusted networks where you would typically already have something like NFS.)

  • If you're root, you can add an entry in /etc/fstab. Note that this will use root's ~/.ssh to look up keys and known hosts.

    example.com:/remote/path /mount/point fuse.sshfs idmap=user,uid=1234
    
  • You can put an @reboot crontab entry.

    @reboot sshfs -o idmap=user example.com:/remote/path /mount/point
    

If you need to type a password to send to the remote server, you need to log in and have a user interface available first. Same thing if you need to type a password to unlock a key.

Most window managers and desktop environments allow you to run custom commands when you log in. You can run a snippet like the following (assuming your environment already starts an SSH agent — most do these days):

SSH_ASKPASS=ssh-askpass ssh-add ~/.ssh/id_rsa
mount | grep ' /mount/point ' ||
sshfs -o idmap=user example.com:/remote/path /mount/point

mount | grep ' /mount/point ' || checks whether the filesystem appears to be mounted already, in case you log in through multiple means. Alternatively, without using an agent:

mount | grep ' /mount/point ' ||
SSH_ASKPASS=ssh-askpass sshfs -o idmap=user example.com:/remote/path /mount/point

If you don't have the ssh-askpass program, another method is to open a terminal just to do the mounting:

xterm -e 'ssh-add ~/.ssh/id_rsa'
mount | grep ' /mount/point ' ||
sshfs -o idmap=user example.com:/remote/path /mount/point

For a text mode log in, put ssh-add in your ~/.profile. Run it only if the shell is interactive.

case $- in
  *i*)
    ssh-add ~/.ssh/id_rsa
    ;;
esac
sshfs -o idmap=user example.com:/remote/path /mount/point
Share:
18,365

Related videos on Youtube

Krutik
Author by

Krutik

Updated on September 18, 2022

Comments

  • Krutik
    Krutik almost 2 years

    Everytime I boot, I use sshfs to mount remote directories. I am thinking to put these short commands in my .bashrc, but that does not seem to be The Right Way™.

    What is the proper way to run sshfs on login?

  • cheshirecatalyst
    cheshirecatalyst over 11 years
    This wouldn't work as written for per-user fuse mounts like sshfs.
  • Mayur A Muley
    Mayur A Muley over 9 years
    We have some issues where this mount (from .bash_profile) will not work if the user logs in shortly after boot - the network (wifi) isn't up yet. A possible solution might be running a script on network up.