, , , , Posted on 19 November 2024 by

Weekly Emacs tip #2: using Tramp for sudo, locally and remote

Tramp is a built-in Emacs “package” that allows you to edit files on remote servers with your local Emacs instance. But it doesn’t only do that, it can also be used to edit files as root via sudo. To achieve this use C-x C-f as you normally would to open a file. However, instead of entering a (local) path, you specify /sudo::/etc/some/file. While entering the path, Emacs will ask you for your password in the minibuffer at the bottom of the screen. This is because (obviously) it is calls sudo . It’s as simple as that 🤓😃. No more sudo-ing in the terminal and then editing a config via root’s Emacs, Vim or Nano.

But it gets even better! Tramp allows you to chain several of its transport mechanisms together using the |. We can use this to edit files on a remove computer using (its) sudo. For example, to edit a file on a remote machine as root (assuming you have sudo permissions on that machine) goes as follows: Start with C-x C-f and type /ssh:user@host.domain|sudo::/etc/some/file. Simple as that.

In both these scenarios it is, of course, a good idea to close the buffers with those files as soon as you’re done. Not only from a security point of view, but also because your sudo will time out and Emacs will ask you again to enter your password. I find that this always happens at an inconvenient time. For example, it seems that changing buffers (C-x b) can also trigger this (maybe because (my?) Emacs tries to see if the sudo-ed file has changed even if I’m not looking at it). The prompt for the password may then disappear from the minibuffer (because of another message) and it will look like Emacs hangs. Often a C-g or two helps to at least cancel the current command and get the password prompt again, but it’s annoying anyway. This can be worked around by storing the password in ~/.authinfo.gpg, but that’s for another time (and maybe makes it a bit too easy to accidentally edit as root??).

No Comments

Let us keep you updated!

Once a month we’ll send you an overview of our newest articles. No spam, we promise.

Thank you for signing up! We've send you an confirmation mail.