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

5.6k views Asked by At

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?

2

There are 2 answers

2
mdornfe1 On BEST ANSWER

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)
0
Jerin Antony On

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)