Skip to main content
 首页 » 编程设计

python之如何使用 sshfs 和 Python 子进程挂载和卸载文件夹

2025年02月15日15linjiqin

我希望能够从 Python 子进程模块挂载然后卸载调用 sshfs 的目录。这是我用来完成此操作的代码。

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) 

mkdir 和 mount 命令成功,但是当我尝试卸载目录时出现错误 umount failed: Operation not permitted。我猜这是因为子进程用户对 local_data_directory 的父文件夹没有写权限。当我检查 local_data_directory 的权限时,它说所有者是用户 #1004。这是 Python 子进程的默认用户吗?我想我可以只为该用户提供对所有父目录的写访问权限,但我不想为我的整个主文件夹提供子进程写权限。有没有办法解决这个问题而不这样做?

请您参考如下方法:

原来解决方案是使用 fusermount 而不是 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)