2

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:
Ali.Turkkan
  • 266
  • 2
  • 11
  • 1
    "cannot execute binary file" is unrelated to your question. The command runs just fine, but fails for external reasons. – tripleee Nov 16 '18 at 07:16
  • I know, I'm getting the print I want after I enter the sudo password. But I want to enter the sudo password automatically with the script and the result can be seen directly in the terminal. @tripleee – Ali.Turkkan Nov 16 '18 at 07:27

1 Answers1

3

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.

damienfrancois
  • 52,978
  • 9
  • 96
  • 110