简体   繁体   中英

How to execute local script as root in remote servers?

I need to execute a shell script with root privileges in remote servers. Those servers can't be connected directly via SSH by root user. Thus, I have to connect ssh as normal user first and then change it to root before execute the script. The user and root passwords are parameters stored previously so keyboard interaction is not an option. In that way I'd need a non-(human)-interactive script like:

#!/bin/sh

username=admin
password=admin123
hosts={host1..host50}

for hostname in $hosts ;
do
   ssh $username@$hostname sudo 'bash -s' < ./test.sh > results.txt
done

How can I do that? In my current code I need to type password for admin user connection and then I have an error like: sudo: no tty present and no askpass program specified . Maybe a command like expect is needed but I don't have much expertise there.

Thanks for your help.

PS: I can't use SSH Keys and administration changes are not allowed in these servers.

So as I understand you can su - into root but you don't want to edit neither sudoers nor ssh keys.
In this case expect is your friend.

Here you can find a quite similar example, but I copy relevant code section here.

#!/usr/bin/expect
set timeout 20

set host [lindex $argv 0]
set password [lindex $argv 1]

spawn ssh -tq $host su - root
expect "ssword" { send "pa55w0rd\r" }   # only if you login with password auth
expect "ssword" { send "$password\r" }
expect "#" { send "id -a \r" }          # run script as root
expect "#" { send \"exit\r" }

Of course you can embed this in a shell script as below.

#!/bin/bash
expect -c "
...
expect eof"

I hope I could help!

Use SSH Keys to avoid having to enter a password

view this link: https://wiki.archlinux.org/index.php/SSH_Keys

If you can modify the sudoers file on the remote host you can tell the sudoer service not to ask password for a specific user to do sudo commands.

sudo visudo

add the directive NOPASSWD to the user

Ubuntu site reference

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM