我想要让 shell 脚本启动sudo apt-get update
后自动输入密码sudo
并自动按回车键。
我试过了:
#!/bin/bash
sudo apt-get update
expect "[sudo] password for username: "
send "password"
答案1
你可以做
#!/bin/bash
echo password | sudo -S apt-get update
从man sudo
和从堆栈溢出
-S
,--stdin
将提示写入标准错误并从标准输入读取密码,而不是使用终端设备。密码后面必须跟换行符。
如果您的密码包含特殊字符,请使用单引号将密码括起来,如echo 'p@ssowrd'
。
答案2
您的想法是正确的,使用expect
正确的工具。但是,您的语法是错误的。请尝试以下操作:
#!/bin/bash
#some instructions ....
#the <<-EOD ... EOD syntax is called a "heredoc" and allows to send multiple instructions to a command
expect <<-EOD
#process we monitor
spawn sudo apt-get update
#when the monitored process displays the string "[sudo] password for username:" ...
expect "[sudo] password for username:"
#... we send it the string "password" followed by the enter key ("\r")
send "password\r"
#we exit our expect block
EOD