12

I'm using the C-x C-f option to use SSH to edit a file.

The file I'm editing requires my SSH user to use sudo.

When I start editing the file it says read-only. How can I remotely edit files requiring sudo?

Philip Kirkbride
  • 557
  • 5
  • 14
  • 2
    I'm not 100% sure what is the convention for dealing with questions already answered elsewhere in the stackexchange network ("cross-site duplicates"), but [this question on stackoverflow](https://stackoverflow.com/questions/2177687/open-file-via-ssh-and-sudo-with-emacs) has a detailed (and looking at the current manual, still up-to-date) answer. – aplaice Nov 21 '17 at 15:14

2 Answers2

15

Using TRAMP multi-hops. For instance, if you want to edit the remote file /root/salary.txt

/ssh:homer@powerplant|sudo:powerplant:/root/salary.txt

The example is taken from the Mastering Emacs book.

Manuel Uberti
  • 3,150
  • 18
  • 36
  • You can omit the second `powerplant` if you stay on the machine you're sshing to. Source: https://www.emacswiki.org/emacs/TrampMode#toc18 . Edit: I was wrong. I didn't read the page thoroughly. – Toon Claes Nov 24 '17 at 18:06
3

I wrote a command for automating @Manuel Uberti's answer. The second one is the one I'd use. It uses the first one for remote files and uses crux for local files.

(require 'crux)
(require 's)

(defun my--reopen-remote-file-as-root ()
  "Reopen a remote file as root over tramp."
  (find-alternate-file (let* ((parts (s-split ":" buffer-file-name))
            (hostname (nth 1 parts))
            (filepath (car (last parts))))
           (concat "/ssh" ":" hostname "|" "sudo" ":" hostname ":" filepath))))


(defun my/reopen-file-as-root ()
  "Reopen a local or remote file as root."
  (interactive)
  (if (file-remote-p default-directory)
      (progn
    (my--reopen-remote-file-as-root)))
  (crux-reopen-as-root))
Hatshepsut
  • 545
  • 3
  • 14