Monday, May 26, 2008
10:18 AM

Root edit a file using emacs in the same session

We know that we should always log in using our regular non-root account, and only sudo in when necessary to do things that only root can do. Most of the time, you are logged in as a regular user, and you have your emacs editor open.

Now, you realize that you need to edit a file which is only writable by root (say /etc/hosts.allow).

What you can always do is to open up another emacs session with the right credential, and edit the file there:
$ sudo emacs /etc/hosts.allow


This becomes a little tedious, doesn't it?

A nifty little trick is to use tramp, an emacs package for transparent remote editing of files using a secure protocol like ssh. You then use tramp to ssh into localhost as root, and modify the target file.

tramp comes pre-packaged within GNU emacs 22+. This is pretty handy, especially if you have already configured and using it to remotely edit files.

If you are new to tramp, insert the following lines into ~/.emacs (your emacs configuration file), and restart emacs:
(require 'tramp)
(setq tramp-default-method "scp")


The scp method for tramp uses ssh to connect to the remote host. In this case, you are merely connecting to localhost as root. This provides security for you as you edit the file as root.

Note that if you are also using the emacs package recentf (for remembering the most recently opened files), insert the following line as well. Otherwise, when you restart emacs in subsequent sessions, it will prompt you for the root password.
(setq recentf-auto-cleanup 'never) 


That is it for configuring tramp for use in emacs.

With this setup, you can use the same emacs session you opened as a non-root user to edit a root-only writable file.

To edit the target file, hit Cntl-x followed by Cntl-f, and enter the following before hitting return:
/su::/etc/hosts.allow


When prompted, enter the password for root.

After you finish editing, save the file as you normally do in emacs.

A final note is that you need to be aware of the side-effects of using tramp to edit a file while the auto backup feature of emacs is enabled. Specifically, make sure that the backup file is saved in an expected safe location. See this article for more details.

StumbleUpon Toolbar

0 comments:

Post a Comment