3
#!/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 ?

  • 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;'" – xwst Apr 5 '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 6 '18 at 6: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 9 '18 at 14:17
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.