nvim 使用 sshfs 连接远程机器

目录
注意
本文最后更新于 2024-07-08,文中内容可能已过时。

nvim 可以通过调用 sshfs,把远程机器上面的文件映射到本地,进而使用本地的 nvim 进行查看与编辑。如此一来,即使远程机器没有安装 nvim 或者相关插件,我们一样也能丝滑地使用 nvim 了。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
return {
    "nosduco/remote-sshfs.nvim",
    dependencies = { "nvim-telescope/telescope.nvim" },
    opts = {
        -- Refer to the configuration section below
        -- or leave empty for defaults
    },
    config = function()
        require('remote-sshfs').setup{
            connections = {
                ssh_configs = { -- which ssh configs to parse for hosts list
                    vim.fn.expand "$HOME" .. "/.ssh/config",
                    "/etc/ssh/ssh_config",
                    -- "/path/to/custom/ssh_config"
                },
                sshfs_args = { -- arguments to pass to the sshfs command
                    "-o reconnect",
                    "-o auto_cache",
                    "-o Ciphers=aes128-ctr",
                    "-o ConnectTimeout=5",
                    "-C",
                    "-o cache_timeout=60",
                    "-o cache=yes",
                },
            },
            mounts = {
                base_dir = vim.fn.expand "$HOME" .. "/.sshfs/", -- base directory for mount points
                unmount_on_exit = true, -- run sshfs as foreground, will unmount on vim exit
            },
            handlers = {
                on_connect = {
                    change_dir = true, -- when connected change vim working directory to mount point
                },
                on_disconnect = {
                    clean_mount_folders = true, -- remove mount point folder on disconnect/unmount
                },
                on_edit = {}, -- not yet implemented
            },
            ui = {
                select_prompts = false, -- not yet implemented
                confirm = {
                    connect = true, -- prompt y/n when host is selected to connect to
                    change_dir = false, -- prompt y/n to change working directory on connection (only applicable if handlers.on_connect.change_dir is enabled)
                },
            },
            log = {
                enable = false, -- enable logging
                truncate = false, -- truncate logs
                types = { -- enabled log types
                    all = false,
                    util = false,
                    handler = false,
                    sshfs = false,
                },
            },
        }
    end
}

使用

可以使用以下命令进行连接

  • :RemoteSSHFSConnect lfang.r9:/home/lfang/git -p22
  • :RemoteSSHFSDisconnect

我们可以映射到快捷键

1
2
3
4
5
local opts = {
    noremap = true, -- non-recursive
    silent = true,  -- do not show message
}
vim.api.nvim_set_keymap("n", "<Leader>rs", ":RemoteSSHFSConnect lfang.r9:/home/lfang/git -p22<CR>", opts)
william 支付宝支付宝
william 微信微信
0%