How to mount and unmount a folder with sshfs and Python Subprocess?

Question:

I want to be able to mount and then unmount a directory calling sshfs from the Python subproccess module. Here is the code I am using to accomplish this.

import subprocess 
mkdir_command = 'mkdir {}'.format(local_data_directory)
unmount_command = 'umount {}'.format(local_data_directory)
mount_command = 'sshfs -o allow_other -o IdentityFile={} {}@{}:{} {}'.format(
    key_file, host_username, host_ip, host_data_directory, local_data_directory)
subprocess.call(mkdir_command, shell=True)
subprocess.call(mount_command, shell=True)
subprocess.call(unmount_command, shell=True)

The mkdir and mount command are successful, but when I try to unmount the directory I get the error umount failed: Operation not permitted. I’m guessing this is because the subprocess user doesn’t have write permission on local_data_directory’s parent folder. When I check the permission’s of local_data_directory it say’s the owner is user #1004. Is this the default user for Python’s subprocess? I guess I could just give that user write access to all of the parent directory’s, but I don’t want to give subprocess write ability for my whole home folder. Is there a way to solve this without doing that?

Asked By: mdornfe1

||

Answers:

Turns out the solution is to use fusermount instead of mount

import subprocess 
mkdir_command = 'mkdir {}'.format(local_data_directory)
unmount_command = 'fuserumount {}'.format(local_data_directory)
mount_command = 'sshfs -o allow_other -o IdentityFile={} {}@{}:{} {}'.format(
    key_file, host_username, host_ip, host_data_directory, local_data_directory)
subprocess.call(mkdir_command, shell=True)
subprocess.call(mount_command, shell=True)
subprocess.call(unmount_command, shell=True)
Answered By: mdornfe1

Its recommended to not use sudo user for sshfs, you can ensure that you have done ssh-copy-id host_username@host_ip and then simply,

import subprocess
mount_command = f'sshfs {host_username}@{host_ip}:{host_data_directory} {local_data_directory}'
subprocess.call(mount_command, shell=True)
# Do your stuff with mounted folder
unmount_command = f'fusermount -u  {local_data_directory}'
subprocess.call(unmount_command, shell=True)
Answered By: Jerin Antony
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.