Doing sudo stuff with tramp
15 Feb 2015Somehow, I accumulated a few files owned by root that should have been
owned by me. Below, I'll describe a solution to get rid of them based
on dired
and tramp
.
Step one: open the directory with sudo privileges
I'll obviously need the sudo privilege to change the owner of a file owned by root. Might as well start with that.
Thankfully, I do have a shortcut:
(defun sudired ()
(interactive)
(require 'tramp)
(let ((dir (expand-file-name default-directory)))
(if (string-match "^/sudo:" dir)
(user-error "Already in sudo")
(dired (concat "/sudo::" dir)))))
(define-key dired-mode-map "!" 'sudired)
The function above will open the current directory in sudo mode. I decided to bind it to !, since the default & seems strictly better than !. The function will ask you for the password once. Afterwards, you can open other directories without having to enter the password.
Step two: find-dired
So now, while in sudo mode of the directory in question:
- Call M-x
find-dired
. It's not bound by default, and I don't bind it myself since it's quite situational (I do bindfind-name-dired
to F indired-mode
though). - It prompts you for the directory. I just press RET, since the default one is what I need.
- Next, it prompts for
find
args. These are the arguments to the UNIX commandfind
. Here, I need to pass-user root
. - The command has finished and I can see the results. I can select
some of them by pressing m (
dired-mark
) a few times, or mark them all at once with t (dired-toggle-marks
). - Finally, call O (
dired-do-chown
) on the marked files and enteroleh
.
Done. I'm sure that the admin types can cook up some find
-exec
-chown
combo to do the same thing,
but the find-dired
approach is both simpler and more flexible, since I can confirm and edit the list
of files being changed.