loading...

Editing remote files with Vim

jovica profile image jovica ・2 min read

One of the lesser known features of Vim is the ability to edit files remotely, over the network.

This feature comes with the netrw plugin. To achieve this, netrw uses the SSH protocol, and manages remote files via the scp command.

Here’s how to do it:

vim scp://user@myserver[:port]//path/to/file.txt

Note the double / for the directory on the remote host, which is needed to correctly resolve the absolute path. [:port] is optional.

So with the command above you can open a file located on a remote host for editing.

What actually happens in the background is that Vim uses scp to download the requested file from a remote machine to a local /tmp directory, and then opens it for editing.

When you save your changes to the file, the changes are first applied to a local copy in /tmp directory. After that, the file is uploaded via scp to the remote host.

If you open a directory on a remote host, you could also use netrw to browse through remote files and directories. The important thing is to always specify the directory path with / at the end.

Of course, it’s recommended that you use SSH keys for authentication. Otherwise, you might be asked for the SSH password too often.

Beside SSH, there are other protocols supported such as sftp, ftp, dav, etc.

For example, to open a file on a remote FTP server, you could run a command like:

vim ftp://hostname/path/to/file

Netrw offers lots of options and possibilities for remote editing, so for more information on this, take a look at :help scp.


What you've just read is an a section of CHAPTER 6. WORKING WITH FILES from the book Mastering Vim Quickly.

Posted on by:

jovica profile

jovica

@jovica

#infosec #sysadmin #gentoo #vim

Discussion

pic
Editor guide
 

Hi there, thanks for your article!

I just learned about that trick recently. VIM is really a wonderful piece of software.

And if you are using ~/.ssh/config to store aliases to your servers, you can even use them to access those servers easily.

$ vim scp://hostAlias//home/user

And using this syntax will bring your VIM explorer which you can access by typing :Explore. Isn't it wonderful to be able to edit remote files from VIM?

If you don't want to quit VIM and execute commands, you can use the :! mycmd syntax to issue commands without quitting vim like :!docker-compose run --rm npm install --save-dev aminnairi/eslint-config and it will just install the packages I need before going back to VIM without quitting my SCP session.

No more VIM configuration on the server needed.

I think I've just found love.

 

Huh never knew about this. On occasion I've used gvim (or xemacs) with X11 forwarding, but over dinky connections it's pretty painful. Nice tip.