I want make shell script to start sudo apt-get update
, automatically insert password for sudo
and automatically hit enter key.
I've tried:
#!/bin/bash
sudo apt-get update
expect "[sudo] password for username: "
send "password"
You can do with
#!/bin/bash
echo password | sudo -S apt-get update
From man sudo
and from Stackoverflow
-S
,--stdin
Write the prompt to the standard error and read the password from the standard input instead of using the terminal device. The password must be followed by a newline character.
If your password has special characters then use single quotes around the password like echo 'p@ssowrd'
.
echo "password"
You got the right idea, using expect
is the right tool. However, your syntax is wrong. Try the following :
#!/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