我正在尝试为一些常用的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)
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
.
小智 5
如果您正在运行 emacs22 或更高版本,您可以从 emacs 启动一个 shell 并在那里运行您的 sudo 命令。它会自动将您拉入迷你缓冲区窗口以获取密码:
M-x shell
sudo whoami
Run Code Online (Sandbox Code Playgroud)
这应该只是在屏幕底部询问您的密码(不显示它)。