Search code examples
bashshellsshsshpass

Using sshpass to run a command on another server


I'm trying to run a single command on server X, to have that SSH into server Y and run another command

I'm doing this like the below:

sshpass -p 'my_password' ssh -t test-admin@my_ip "sudo su c command_must_be_run_root --arguments"

So to break it down:

  • I'm using "sshpass" to pass a password into my ssh command
  • I'm SSH'ing into the new server as the "test-admin" user
  • once in the server, I am running the command "sudo su command_must_be_run_root --arguments
    • This "command_must_be_run_root" is a command that has to be run as root only
    • It also has arguments I have to pass in. However I'm seeing that when I pass in the arguments, it is passing these arguments into the "su" command, and not passing them into the new command I want to run

Any ideas on how to fix this?


Solution

  • For what ever reason when you have a command with arguments you need to actually tell sudo su to login as root. Without logging in first it will run the first part of the command, even with all of it in single quotes, but not the args. (I guess it thinks that is the end of the command or it's only 1 command per sudo su -c, and that is why the persistent login works?). After adding sudo su -l root then you can continue with -c and everything that follows needs single quotes.

    Should look like this: sshpass -p 'my_password' ssh -t test-admin@my_ip "sudo su -l root -c 'command_ran_as_root --arguments'"