Can vim edit a remote file as root?

I'm going to say this is not possible because vim is not executing remote commands. It is simply using scp to copy the file over, edit it locally and scp it back when done. As stated in this question sudo via scp is not possible and it is recommended that you either modify permissions to accomplish what you're wanting or just ssh across to the remote machine.


Like the accepted answer, I don't think this is possible directly.

However, I see at least two ways to still accomplish your goal.

Running vim remotely

ssh user@myserver sudo vim /some/file

This has disadvantages:

  • Your interactions with vim go over the network. Significant lag will be annoying, and if your connection dies, so does vim (eventually).
  • This won't use your local vim config, but remote's root's vim config.

But it has the advantage of working.

Doing the scp outside of vim

You could just copy the file over locally, edit it, and copy it back. And you could automate that to make it almost as seamless as vim's scp support.

Something like the following shell script could work (note, fully untested!):

#! /bin/sh

TMPFILE=$(mktemp)
ssh -- "$1" sudo cat "'$2'" > ${TMPFILE}
vim ${TMPFILE}
ssh -- "$1" "sudo tee '$2' > /dev/null" < ${TMPFILE} && \
  rm -f ${TMPFILE}

This would allow you to do something like rvim user@myserver /some/file. It even keeps the local copy if the second transfer fails, so you don't lose your changes.

The script could use many improvements (at the very least error checking), but it's a starting point.


You would need the root password or have your public ssh key in ~root/.ssh/authorized_keys. Once you had that, you could probably do

vim scp://root@nagios//tmp/notouch

Bottom line: this is effectively just a shortcut for

scp root@nagios:/tmp/notouch /tmp/notouch
vim /tmp/notouch
scp /tmp/notouch root@nagios:/tmp/notouch

If you have the necessary access to do that, then you have the necessary access to use vim's network access plugin. If not, then you don't.

As Zachary Brady points out, sudo is not involved. You'll need ssh access to the root account.

Have you tried it?

Tags:

Vim

Sudo

Remote