2

I love eshell's TRAMP integration. With it I can do cd /ssh:foo:/etc to ssh into a remote machine and visit its /etc/ directory. I can also do find-file motd to open this file in my local emacs. However, what if I need to use sudo to change the file? I know I can give the full path, like so:

find-file /sudo:foo:/etc/motd

but is there a way to open the file via TRAMPs sudo support, without having to type the full path?

tripleee
  • 175,061
  • 34
  • 275
  • 318
Stig Brautaset
  • 2,602
  • 1
  • 22
  • 39

2 Answers2

1

I managed to came up with the following eshell alias that works for me:

alias sff 'find-file "${pwd}/$1"(:s/ssh/sudo/)'

It should be fairly obvious what it does. It prepends the working directory path, but with the string ssh replaced by sudo. Thus it only works for remote files accessed over ssh. I rarely edit files using sudo locally, so that's not a problem for me. However, we can make it work for local files too, at the cost of complexity:

alias sff 'find-file "${pwd}/$1"(:s,^,/sudo::,:s,::/ssh:,:,)'

That is, prepend /sudo:: (which is how to sudo for local files) and subsequently replace any ocurrence of ::/ssh: with :. (I would have just removed :/ssh:, but eshell's :s/// construct didn't accept an empty replacement.)

Stig Brautaset
  • 2,602
  • 1
  • 22
  • 39
0

I found an alternative answer that works very well over at EmacsWiki. Using that you'd still open the file with find-file as usual, but then invoke M-x sudo-edit-current-file (shown below) to re-open the file as root using Tramp. I think this is a very elegant solution, because often I initially just want to look at a file, then later find that I need to edit it.

Here's the function, in case it disappears from the page above:

(set-default 'tramp-default-proxies-alist (quote ((".*" "\\`root\\'" "/ssh:%h:"))))
(require 'tramp)
(defun sudo-edit-current-file ()
  (interactive)
  (let ((position (point)))
    (find-alternate-file
     (if (file-remote-p (buffer-file-name))
         (let ((vec (tramp-dissect-file-name (buffer-file-name))))
           (tramp-make-tramp-file-name
            "sudo"
            (tramp-file-name-user vec)
            (tramp-file-name-host vec)
            (tramp-file-name-localname vec)))
       (concat "/sudo:root@localhost:" (buffer-file-name))))
    (goto-char position)))
Stig Brautaset
  • 2,602
  • 1
  • 22
  • 39