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
How to Configure Acpi *.Asl for a Virtual Mdio-Gpio Device Connected to a I2C Gpio Expander
Run Bash Script in Raspberry Pi via Ifttt
Stack Smashing Code Not Working on Linux Kernel 2.6.38.7... Please Help
Omnisharp.Msbuild.Projectmanager Failed to Load Project on Linux
How to Set a Non-Standard Baudrate on a Serial Port Device on Linux
How to Draw 2D Diagram in Linux
Mathematical Expression Result Assigned to a Bash Variable
Delete Last Line Break Using Sed
Script to Check for Process & Restart Program If Not Found
Perf Tool Stat Output: Multiplex and Scaling of "Cycles"
Linking to Modules Folder Gives Undefined Reference
In Bash How to Split a Column in Several Column of Fixed Dimension
Gnuplot Doesn't Work Through Ssh Command
Reading Input from Keyboard with X64 Linux Syscalls (Assembly)