sshfsで別サーバのディレクトリをマウントする

sshfsを使用して別サーバのディレクトリをマウントする手順について説明しています。

sshfsについて

sshfsはsshを経由して他のサーバのディレクトリをマウントすることができます。

一度sshfsでマウントしてしまえば、データをコピーする際に毎回scpやrsyncなどのコマンドを使わずとも、cpコマンドで簡単にデータをコピーできるのでとても便利ですね。

sshfsのインストール

CentOSの場合は標準のリポジトリには含まれていないので、「epel」リポジトリを使用してインストールを行う必要があります。

# yum install --enablerepo=epel sshfs

「epel」リポジトリの追加手順はこちらのページを参考にしてください。

sshfsの使用方法

「sshfs」の使用方法について説明していきます。

マウント方法

「sshfs」を使用して別サーバのディレクトリをマウントする方法は下記の通りとなります。

sshfs [ユーザ名@]ホスト:[ディレクトリ] マウントディレクトリ [オプション]

マウント例

今回は「/home/tamohiko/test5」というディレクトリに「test5.server-memo.net」サーバの「tamohiko」ユーザのホームディレクトリをマウントしていきます。

実際にマウント作業を行うにあたり、まずはマウントさせるためのディレクトリを作成します。

$ mkdir /home/tamohiko/test5

次に「sshfs」コマンドを使ってマウントを行います。

$ sshfs tamohiko@test5.server-memo.net:/home/tamohiko /home/tamohiko/test5

マウント作業が完了しましたら、「df」コマンドでマウントされているか確認してみます。

$ df -h | grep test5
tamohiko@test5.server-memo.net:/home/tamohiko    48G   33M   48G    1% /home/tamohiko/test5

無事マウントされていることが確認できました。

アンマウント方法(マウント解除)

sshfsでマウントしたディレクトリをアンマウントする場合は「fusermount -u」コマンドを使用します。

fusermount -u マウントディレクトリ

アンマウント例

実際に先ほどマウントした「/home/tamohiko/test5/」ディレクトをアンマウントしてみます。

$ fusermount -u /home/tamohiko/test5/

実際にアンマウントされたかを「df」コマンドで確認してみます。

$ df -h | grep test5

何も表示されなかったので、無事アンマウントされていることが確認できました。

Device or resource busy で解除できない場合

マウントしているディレクトリを使用していない場合でも「fusermount -u 」コマンドでアンマウントが出来ない場合があります。

$ fusermount -u /home/tamohiko/test5
fusermount: failed to unmount /home/tamohiko/test5: Device or resource busy

この場合は「root」ユーザで「umount -l」を使用すると強制的にアンマウントすることが出来ます。

umount -l マウントポイント

実際にマウントされているディレクトリをアンマウントしてみます。

# umount -l /home/tamohiko/test5

コマンド実行後「df」コマンドでアンマウントされているか確認してください。

オプションについて

「sshfs」で使用できるオプションはとても多いので、普段使用しそうなものについて説明していきます。

ポートの変更 (-p ポート番号 | -o port=ポート番号)

SSHの待ち受けポートがデフォルトの「22」番ポートから変更されている場合は、「-p」か「-o port=ポート番号」を使用することで接続先ポート番号を指定することが出来ます。

-p ポート番号
-o port=ポート番号

使用例

「20222」番ポートを指定してマウントをする場合は、下記のように指定することになります。

「-p ポート番号」を使用
$ sshfs tamohiko@192.168.1.105:/home/tamohiko /home/tamohiko/test5 -p 20222
「-o port=ポート番号」を使用
$ sshfs tamohiko@192.168.1.105:/home/tamohiko /home/tamohiko/test5 -o port=20222

秘密鍵を指定 (-o IdentityFile)

SSHの接続が鍵認証方式となっている場合は、「-o IdentityFile」オプションを使用して秘密鍵を指定します。

-o IdentityFile=秘密鍵

使用例

秘密鍵を指定する場合は下記のように指定をします。

$ sshfs tamohiko@192.168.1.105:/home/tamohiko /home/tamohiko/test5 -p 20222 -o IdentityFile=/home/tamohiko/.ssh/id_ecdsa

他のユーザもアクセス許可(-o allow_other)

「sshfs」を使用してマウントしたディレクトリは、通常マウントしたユーザのみ使用できます。

他のユーザにも使用許可させるには「-o allow_other」オプションを使用します。

「tamohiko」ユーザが「sshfs」でマウントした状態で「df」コマンドを実行すると、マウントされたディレクトリの情報が表示されています。

$ id
uid=1000(tamohiko) gid=1000(tamohiko) groups=1000(tamohiko)
$ df
ファイルシス                  1K-ブロック    使用   使用可 使用% マウント位置
/dev/mapper/cl-root              17811456 1239636 16571820    7% /
devtmpfs                           489248       0   489248    0% /dev
tmpfs                              499960       0   499960    0% /dev/shm
tmpfs                              499960    6860   493100    2% /run
tmpfs                              499960       0   499960    0% /sys/fs/cgroup
/dev/sda1                         1038336  151388   886948   15% /boot
tmpfs                               99992       0    99992    0% /run/user/1000
tamohiko@test5:/home/tamohiko    49725724   33136 49692588    1% /mnt/test5

別ユーザで「df」コマンドを実行してみると、マウントされているディレクトリが見えない状態となっています。

$ id
uid=1002(test) gid=1002(test) groups=1002(test)
$ df
ファイルシス        1K-ブロック    使用   使用可 使用% マウント位置
/dev/mapper/cl-root    17811456 1239616 16571840    7% /
devtmpfs                 489248       0   489248    0% /dev
tmpfs                    499960       0   499960    0% /dev/shm
tmpfs                    499960    6860   493100    2% /run
tmpfs                    499960       0   499960    0% /sys/fs/cgroup
/dev/sda1               1038336  151388   886948   15% /boot
tmpfs                     99992       0    99992    0% /run/user/1000

ちなみに、直接マウントポイントに移動することも出来ません。

$ cd /mnt/test5
-bash: cd: /mnt/test5: 許可がありません

/etc/fuse.conf 編集

一般ユーザが「-o allow_other」を使用するには、最初に「/etc/fuse.conf」に「user_allow_other」の設定を追加する必要があります。

# cp -p /etc/fuse.conf /etc/fuse.conf_yyyymmdd
# vi /etc/fuse.conf

※「fuse.conf」ファイルが無い場合は新規に作成する必要があります。

編集前

CentOS7の場合は下記のように「user_allow_other」がコメント化されていますので、「#」を削除して有効化してあげてください。

# mount_max = 1000
# user_allow_other
編集後
# mount_max = 1000
user_allow_other

この設定を行わずに一般ユーザが「-o allow_other」オプションを使用すると、下記メッセージが表示されてマウントすることが出来ません。

fusermount: option allow_other only allowed if 'user_allow_other' is set in /etc/fuse.conf

「-o allow_other」を使用してマウント

「tamohiko」ユーザで「test5」サーバのディレクトリを「-o allow_other」オプションを指定して「/mnt/test5」にマウントします。

$ sshfs tamohiko@test5:/home/tamohiko /mnt/test5 -o allow_other

次に、「test」ユーザでマウントしたディレクトリを使用できるか確認してみます。

$ id
uid=1002(test) gid=1002(test) groups=1002(test)
$ df -h
ファイルシス                  サイズ  使用  残り 使用% マウント位置
/dev/mapper/cl-root              17G  1.2G   16G    7% /
devtmpfs                        478M     0  478M    0% /dev
tmpfs                           489M     0  489M    0% /dev/shm
tmpfs                           489M  6.7M  482M    2% /run
tmpfs                           489M     0  489M    0% /sys/fs/cgroup
/dev/sda1                      1014M  148M  867M   15% /boot
tmpfs                            98M     0   98M    0% /run/user/1000
tamohiko@test5:/home/tamohiko    48G   33M   48G    1% /mnt/test5

「df」コマンドでマウントされているディレクトリが確認できたので、次に移動出来るか確認してみます。

$ cd /mnt/test5/
$ pwd
/mnt/test5

無事対象ディレクトリに移動できることも確認できました。

複数オプションの指定方法

複数のオプションをまとめて指定する場合は「,」で区切ることで、一度に複数のオプションを指定することが出来ます。

-o allow_other,compression=yes,transform_symlinks,idmap=user

オプション一覧

sshfsのオプション一覧です。必要に応じて使用してください。

general options:
    -o opt,[opt...]        mount options
    -h   --help            print help
    -V   --version         print version

SSHFS options:
    -p PORT                equivalent to '-o port=PORT'
    -C                     equivalent to '-o compression=yes'
    -F ssh_configfile      specifies alternative ssh configuration file
    -1                     equivalent to '-o ssh_protocol=1'
    -o reconnect           reconnect to server
    -o delay_connect       delay connection to server
    -o sshfs_sync          synchronous writes
    -o no_readahead        synchronous reads (no speculative readahead)
    -o sync_readdir        synchronous readdir
    -o sshfs_debug         print some debugging information
    -o cache=BOOL          enable caching {yes,no} (default: yes)
    -o cache_timeout=N     sets timeout for caches in seconds (default: 20)
    -o cache_X_timeout=N   sets timeout for {stat,dir,link} cache
    -o workaround=LIST     colon separated list of workarounds
             none             no workarounds enabled
             all              all workarounds enabled
             [no]rename       fix renaming to existing file (default: off)
             [no]nodelaysrv   set nodelay tcp flag in sshd (default: off)
             [no]truncate     fix truncate for old servers (default: off)
             [no]buflimit     fix buffer fillup bug in server (default: on)
    -o idmap=TYPE          user/group ID mapping, possible types are:
             none             no translation of the ID space (default)
             user             only translate UID of connecting user
             file             translate UIDs/GIDs contained in uidfile/gidfile
    -o uidfile=FILE        file containing username:remote_uid mappings
    -o gidfile=FILE        file containing groupname:remote_gid mappings
    -o nomap=TYPE          with idmap=file, how to handle missing mappings
             ignore           don't do any re-mapping
             error            return an error (default)
    -o ssh_command=CMD     execute CMD instead of 'ssh'
    -o ssh_protocol=N      ssh protocol to use (default: 2)
    -o sftp_server=SERV    path to sftp server or subsystem (default: sftp)
    -o directport=PORT     directly connect to PORT bypassing ssh
    -o slave               communicate over stdin and stdout bypassing network
    -o disable_hardlink    link(2) will return with errno set to ENOSYS
    -o transform_symlinks  transform absolute symlinks to relative
    -o follow_symlinks     follow symlinks on the server
    -o no_check_root       don't check for existence of 'dir' on server
    -o password_stdin      read password from stdin (only for pam_mount!)
    -o SSHOPT=VAL          ssh options (see man ssh_config)

FUSE options:
    -d   -o debug          enable debug output (implies -f)
    -f                     foreground operation
    -s                     disable multi-threaded operation

    -o allow_other         allow access to other users
    -o allow_root          allow access to root
    -o auto_unmount        auto unmount on process termination
    -o nonempty            allow mounts over non-empty file/dir
    -o default_permissions enable permission checking by kernel
    -o fsname=NAME         set filesystem name
    -o subtype=NAME        set filesystem type
    -o large_read          issue large read requests (2.4 only)
    -o max_read=N          set maximum size of read requests

    -o hard_remove         immediate removal (don't hide files)
    -o use_ino             let filesystem set inode numbers
    -o readdir_ino         try to fill in d_ino in readdir
    -o direct_io           use direct I/O
    -o kernel_cache        cache files in kernel
    -o [no]auto_cache      enable caching based on modification times (off)
    -o umask=M             set file permissions (octal)
    -o uid=N               set file owner
    -o gid=N               set file group
    -o entry_timeout=T     cache timeout for names (1.0s)
    -o negative_timeout=T  cache timeout for deleted names (0.0s)
    -o attr_timeout=T      cache timeout for attributes (1.0s)
    -o ac_attr_timeout=T   auto cache timeout for attributes (attr_timeout)
    -o noforget            never forget cached inodes
    -o remember=T          remember cached inodes for T seconds (0s)
    -o intr                allow requests to be interrupted
    -o intr_signal=NUM     signal to send on interrupt (10)
    -o modules=M1[:M2...]  names of modules to push onto filesystem stack

    -o max_write=N         set maximum size of write requests
    -o max_readahead=N     set maximum readahead
    -o max_background=N    set number of maximum background requests
    -o congestion_threshold=N  set kernel's congestion threshold
    -o async_read          perform reads asynchronously (default)
    -o sync_read           perform reads synchronously
    -o atomic_o_trunc      enable atomic open+truncate support
    -o big_writes          enable larger than 4kB writes
    -o no_remote_lock      disable remote file locking
    -o no_remote_flock     disable remote file locking (BSD)
    -o no_remote_posix_lock disable remove file locking (POSIX)
    -o [no_]splice_write   use splice to write to the fuse device
    -o [no_]splice_move    move data while splicing to the fuse device
    -o [no_]splice_read    use splice to read from the fuse device

Module options:

[iconv]
    -o from_code=CHARSET   original encoding of file names (default: UTF-8)
    -o to_code=CHARSET      new encoding of the file names (default: UTF-8)

[subdir]
    -o subdir=DIR           prepend this directory to all paths (mandatory)
    -o [no]rellinks         transform absolute symlinks to relative

サーバ起動時にマウント

サーバを起動した際に自動的にマウントさせたい場合は、下記の書式で「/etc/fstab」に記述することで自動マウントさせることが出来ますが、この場合SSHは鍵認証方式に対応していて、鍵にパスワードが設定されていないことが前提となります。

/bin/sshfs#[ユーザ名@]ホスト:[ディレクトリ] マウントディレクトリ fuse [オプション] 0 0 

ちょっと長くなってしまいましたが、下記が実際の記述例となります。

/bin/sshfs#tamohiko@192.168.1.105:/home/tamohiko /mnt/test5 fuse IdentityFile=/home/tamohiko/.ssh/id_ecdsa,allow_other,compression=yes,transform_symlinks,idmap=user,reconnect,_netdev,ServerAliveInterval=60 0 0

今回指定しているオプションは以下のものになっています。

  • IdentityFile= SSHの秘密鍵を指定
  • allow_other 他ユーザのアクセス許可
  • compression=yes 通信の圧縮を行う
  • transform_symlinks マウント内で完結するsymlinkを相対パスに変更
  • idmap=user 接続ユーザのみuidを変換する
  • reconnect サーバに再接続
  • _netdev ネットワーク開始までマウントを待機する
  • ServerAliveInterval= ホストと応答確認を行う間隔

「IdentityFile=」「_netdev」は必須ですが、それ以外は必要に合わせて指定してください。

コメント

タイトルとURLをコピーしました