Ubuntu 20.04 挂载 SFTP 远程目录,通常使用 SSHFS 工具,它通过 SSH 协议将远程 SFTP 目录映射为本地文件系统。以下是完整步骤:


1. 安装 SSHFS

sudo apt update
sudo apt install sshfs fuse

2. 创建本地挂载点

mkdir -p ~/remote-mount
# 或使用系统目录
sudo mkdir -p /mnt/remote-server

3. 手动挂载(临时)

密码登录方式:

sshfs user@remote_host:/remote/path ~/remote-mount

密钥登录方式(推荐):

sshfs -o IdentityFile=~/.ssh/id_rsa user@remote_host:/remote/path ~/remote-mount

非标准端口(如 2222):

sshfs -p 2222 -o IdentityFile=~/.ssh/id_rsa user@remote_host:/remote/path ~/remote-mount

常用优化参数:

sshfs user@host:/path ~/local \
  -o reconnect,ServerAliveInterval=15,ServerAliveCountMax=3 \
  -o cache=yes,allow_other

参数说明:

  • reconnect:网络中断后自动重连
  • ServerAliveInterval=15:每15秒检测连接状态
  • cache=yes:启用缓存提升性能

4. 配置开机自动挂载(/etc/fstab)

编辑 fstab 文件:

sudo nano /etc/fstab

添加以下行(按需选择方案):

方案 A:基础配置(密码/密钥均可,但密钥更稳定)

user@host:/remote/path  /local/mountpoint  fuse.sshfs  defaults,_netdev  0  0

方案 B:推荐配置(按需挂载 + 密钥认证 + 自动重连)

user@host:/remote/path  /local/mountpoint  fuse.sshfs  noauto,x-systemd.automount,_netdev,user,idmap=user,IdentityFile=/home/localuser/.ssh/id_rsa,allow_other,reconnect  0  0

方案 C:多用户访问 + 权限映射

user@host:/remote/path  /local/mountpoint  fuse.sshfs  defaults,allow_other,_netdev,uid=1000,gid=1000  0  0

⚠️ 关键:自动挂载必须配置 SSH 免密登录(密钥认证),否则开机时会因无法输入密码而挂载失败。


5. 配置 SSH 免密登录(自动挂载必需)

# 生成密钥(如已有可跳过)
ssh-keygen -t ed25519

# 复制公钥到远程服务器
ssh-copy-id user@remote_host

# 测试免密登录
ssh user@remote_host

6. 验证与测试

# 测试 fstab 配置是否正确(不重启)
sudo mount -a

# 查看挂载状态
df -h | grep remote-mount

# 查看挂载详情
mount | grep sshfs

7. 卸载

# 卸载指定目录
fusermount -u ~/remote-mount
# 或
sudo umount ~/remote-mount

常见问题排查

问题 解决方案
Transport endpoint is not connected fusermount -u 挂载点 后重新挂载
权限不足 添加 allow_other 参数,并确保 /etc/fuse.confuser_allow_other 已取消注释
开机挂载失败 使用 noauto,x-systemd.automount 实现按需挂载,避免网络未就绪时尝试挂载
防火墙拦截 确保远程服务器的 22 端口(或自定义端口)可访问