5

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"
0

2 Answers 2

7

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'.

2
  • 1
    you'll need to add proper quotation for it to work if the password has special characters in it. i.e. echo "password"
    – Aserre
    Mar 2, 2017 at 10:31
  • 3
    This works, but I would warn you, that it is easy for an intruder to find the password, when you have it in clear text in a shellscript like this.
    – sudodus
    Mar 2, 2017 at 10:36
1

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

Not the answer you're looking for? Browse other questions tagged .