Execute Sudo Using Expect Inside Ssh from Bash

Bash: Running a function as sudo on remote host?

The suggestion from @Will is helpful in this instance, using sudo bash -c, then declaring and running the function:

sudo bash -c "$(declare -f runOnRemoteHostAsRoot); runOnRemoteHostAsRoot"

We'll use that line after passing the password through sshpass for passwordless login, like this:

echo '${SSHPASS}' | sudo --stdin bash -c '$(declare -f runOnRemoteHostAsRoot); runOnRemoteHostAsRoot'`

So using this in the above example:

#!/bin/bash

read SSHPASS
export SSHPASS

runOnRemoteHost() {
# ...
whoami
# ...
}
# ...
sshpass -e ssh -o PasswordAuthentication=yes "user@remotehost" "$(declare -f runOnRemoteHost); runOnRemoteHost" 2>&1
# ...

runOnRemoteHostAsRoot() {
# ...
whoami
# ...
}
# ...
sshpass -e ssh -o PasswordAuthentication=yes "user@remotehost" "echo '${SSHPASS}' | sudo --stdin bash -c '$(declare -f runOnRemoteHostAsRoot); runOnRemoteHostAsRoot'" 2>&1

Output:

user
root

Make the ssh connection and enter the sudo password fully automatically

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.

SSH sudo inside script different behaviour

Don't run script.sh with sudo on computerA; instead modify the script like so:

sudo cp /dir1/file1 /dir2/file2
ssh username@ComputerB "sudo reboot"

The reason that you're seeing the strange behaviour is that you're actually becoming root on computerA (I assume you have a keypair set-up for your regular user and expect to connect to computerB passwordless?), and that root on computerA doesn't have a keypair that computerB knows about.



Related Topics



Leave a reply



Submit