0
votes

I've been working on a bash script that automatically runs certain scripts on remote machines and saves the logs to certain folders. As of now I have been copying the local script to the remote machine, executing it into a remote log, copying the remote log into a local folder, and then deleting the remote log and remote copy of the script.

This works, but I know it can work better if I can avoid doing all the in between steps. The one caveat is I need this to be automatic and passwordless (meaning no user input at all). One of the scripts needs to be ran as root or it won't display all the necessary information and will userlock the machine temporarily.

The code I am currently using to execute the remoteScript into a log that I later retrieve with scp is below.

sshpass -f password.txt ssh [email protected] "echo $password | sudo -S /home/user/remoteScript.sh > remoteLog.txt"

And in my testing, execution of local script on remote machine into local log file works like below

sshpass -f password.txt ssh [email protected] "bash -s" < /home/user/localScript.sh >> localLog.txt

How could I combine the elements of the two code examples above in order to make a local script run on a remote machine with root privilege and log the output into a local text file?

Some things I have tried that do not work include:

sshpass -f password.txt ssh [email protected] "bash -s" < "echo $password | sudo -S /home/user/script.sh >> log.txt"
sshpass -f password.txt ssh [email protected] "echo $password | sudo -S /home/user/script.sh" >> log.txt

and notably

sshpass -f password.txt ssh [email protected] echo $password | sudo -S /home/user/script.sh >> log.txt

which just executes the local script with root privilege on the local machine.

I have tried many variations of the above commands and I believe its some sort of piping or flow issue but I cannot figure it out. Is there anyway to do this?

Machines are Ubuntu 16.04 and you cannot ssh in already as root.

Thanks in advance

1

1 Answers

1
votes

A) It might be worth looking into an orchestration/config management solution (e.g. ansible). It's a steep learning curve at first, but initial outlay will pay off on spades down the line if you're managing multiple servers.

B) Setup password-less sudo for the scripts you want to execute, so you don't have to pass around the password in plaintext, and can run without any input. In sudoers:

user ALL=(ALL) NOPASSWD:/home/user/script.sh

C) Setup an SSH key, so you don't need to use a password at all.

But in nutshell, the code you're looking for is something like:

cat /home/user/localScript.sh | ssh [email protected] "sudo bash" > log.txt

Which executes a non-interactive bash shell as root on the remote machine, which will take commands to execute on standard in, and the standard output will come back over the ssh channel for you to write to your local log. Look into &> or 2>&1 if you want standard error too.