Search code examples
bashexpectopensshpwd

Make the ssh connection and enter the sudo password fully automatically


I want to make ssh connection automatically and install a packet to the connected machine. I'm able to process the SSH connection automatically. I can even run commands that do not require sudo authorization. But I didn't find a way to automatically enter the password in the commands that require sudo authorization. How do you think I can automatically enter the sudo password?

asd.sh

/usr/bin/expect -c 'spawn ssh -t usr@ip bash "pwd; sudo apt-get update"; expect "password:"; send "12345\r"; interact;'

asd.sh output

spawn ssh -t usr@ip bash pwd; sudo apt-get update
usr@ip's password: 
/bin/pwd: /bin/pwd: cannot execute binary file
[sudo] password for usr:

Solution

  • You need the -c argument to pass a command string to Bash. Also, try to have the pattern match the full line. Try with:

    /usr/bin/expect -c 'spawn ssh -t usr@ip bash -c "pwd; sudo apt-get update"; expect "*password:"; send "12345\r"; interact;'
                                                 ^^                                     ^
    

    Note that for this kind of task, Ansible can be very helpful as it will take care of all the boilerplate related to SSH and SUDO, and offers high-level modules to carry on any task easily.

    The Ansible script ('playbook') would look like this (untested):

    - hosts: ip
      tasks: 
        - name: Update and upgrade apt packages  
          become: true
          apt:
            upgrade: yes
    

    You can store the SUDO password in a file, and that file can be encrypted.