如何在Emacs中运行sudo命令?

Ina*_*thi 14 emacs shell sudo

我正在尝试为一些常用的sudo shell命令创建快捷键(例如,C-c s运行(shell-command "sudo /etc/init.d/apache2 restart")).

我尝试使用如上所述的直接shell命令调用,但它只是将以下内容输出到*Shell Command Output*缓冲区:

[sudo] password for Inaimathi:
Sorry, try again.
[sudo] password for Inaimathi:
Sorry, try again.
[sudo] password for Inaimathi:
Sorry, try again.
sudo: 3 incorrect password attempts
Run Code Online (Sandbox Code Playgroud)

它实际上并没有要求输入密码.我不想要启动Emacs使用sudo emacs,但我想这是一个选项,如果没有其他工作.

理想的解决方案是Emacs中的一个函数(而不是OS jiggery-pokery来改变shell或sudo命令的行为).喜欢的东西(sudo-shell-command "dostuff"),或者(with-password-prompt (shell-command "sudo dostuff")).

sco*_*zer 13

怎么样:

(shell-command (concat "echo " (shell-quote-argument (read-passwd "Password? "))
                       " | sudo -S your_command_here"))
Run Code Online (Sandbox Code Playgroud)

  • 完美的。换句话说,我可以轻松地执行类似 `(defun sudo-shell-command (command) (shell-command (concat "echo " (read-passwd "Password: ") " | sudo -S " command)))` 的操作。也比在源代码中实际编写密码要好得多。 (2认同)

Mir*_*lov 11

我经常从Emacs调用命令aptitude update.scottfrazer的解决方案可能没那么有用.同步命令让我等了很长时间,如果你执行一个不支持的程序(例如,aptitude使用ncurses),你将挂断Emacs(C-g没有帮助),CPU负载将是100%.改变以async-shell-command解决这个问题.

但它也引入了一个新问题.如果您的命令失败,您的密码将以*Messages*缓冲区结束:

echo PASSWORD | sudo -S aptitude: exited abnormally with code 1.
Run Code Online (Sandbox Code Playgroud)

这就是我提出以下解决方案的原因:

(defun sudo-shell-command (command)
  (interactive "MShell command (root): ")
  (with-temp-buffer
    (cd "/sudo::/")
    (async-shell-command command)))
Run Code Online (Sandbox Code Playgroud)

这里"M"在interactive迷你缓冲区中提示程序名称,with-temp-buffer创建一个假缓冲区,我们将目录更改/sudo::/为使用TRAMP进行sudo提示.

这是来自sudo命令的David Kastrup 使用迷你缓冲区密码提示@ gnu.emacs.help的解决方案.

注意,您仍然不应该aptitude直接调用,否则子进程将永远存在,直到您发送sudo pkill aptitude.

阅读手册中的shell过程.


小智 5

如果您正在运行 emacs22 或更高版本,您可以从 emacs 启动一个 shell 并在那里运行您的 sudo 命令。它会自动将您拉入迷你缓冲区窗口以获取密码:

M-x shell
sudo whoami
Run Code Online (Sandbox Code Playgroud)

这应该只是在屏幕底部询问您的密码(显示它)。