5
#!/bin/bash
while IFS="," read -r f1 f2
do
 username="testuser"
 SSHPASS='abcde' sshpass -e ssh -t "$username@$f1" "sudo su - root -c 'yum -y install wget'"< /dev/null ;  
done < Input.txt

Now i would like to not only get wget installed, but execute a script.
eg: Grep and check if services are running, Remove unwanted folders, etc.
I've tried this:

#!/bin/bash
while IFS="," read -r f1 f2
do
  username="testuser"
  SSHPASS='abcde' sshpass -e ssh -t "$username@$f1" "sudo su - root -c
  if [ -d /opt/xxxx ]; then
    rm -rf /opt/xxxx
  if [ -d /etc/xxxx ]; then
    rm -rf /etc/xxxx
  fi"< /dev/null ;
done < Input.txt

It seems not to work. How could I pass a script to execute as root on a remote machine ?

Kiwy
  • 9,415
  • 13
  • 49
  • 79
Anna
  • 51
  • 1
  • 2
  • What is your error message? You missed a "fi;" statement after the line "rm -rf /opt/xxxx" and you should probably write all statements in one line using ';' to separate statements. This worked for me: ssh -t localhost "sudo su - root -c 'if [ -d /opt/xxxx/ ]; then ls /opt/xxxx/; fi; if [ -d /etc/ ]; then echo \"etc exists\"; fi;'" – staxyz Apr 05 '18 at 10:00
  • i have made changes in the code and added if and fi properly. Please find the error faced.---------- Pseudo-terminal will not be allocated because stdin is not a terminal. Pseudo-terminal will not be allocated because stdin is not a terminal. ssh: Could not resolve hostname : Name or service not known Pseudo-terminal will not be allocated because stdin is not a terminal. ssh: Could not resolve hostname : Name or service not known – Anna Apr 06 '18 at 06:06
  • Your "could not resolve hostname" error is pretty self explanatory. What happens when you do `nslookup hostname` or `dig +short hostname`, where "hostname" is your remote host. – L.Ray Apr 09 '18 at 14:17

1 Answers1

2

Running multiple commands with sudo can be done in multiple ways, see https://www.cyberciti.biz/faq/how-to-run-multiple-commands-in-sudo-under-linux-or-unix/

For example the followwing will produce two lines of output, the first containing a timestamp of your local machine, the second 'root'.

sudo -- sh -c 'date; whoami'

You can give this to ssh in double quotes to execute it on a remote machine. Like the following.

ssh [options] "sudo -- sh -c 'date; whoami'"

The [options] should be replaced by whatever options you want to give to ssh, including the remote hostname.