Chris Bolton
Chris Bolton

Reputation: 2314

sudo su with user name, password and command

I am trying to do something like

echo 'my_password' | sudo -S su -c some-user ./some_command

I have looked at

How can I apply password to sudo in one line command and execute su root?

and

run a sudo command, specifying the password on the same line

But neither of these really answer my question above.

I am still getting the password prompt for my user.

Upvotes: 0

Views: 7105

Answers (2)

Lam Nguyen
Lam Nguyen

Reputation: 31

You can use expect. First install the expect rpm then run command look like this:

expect -c "spawn sudo /tmp/test.sh; sleep 3; expect -re \"password\"; send \"mypassword\r\n\";set timeout 5;expect -re \"time=\";"

Upvotes: 0

Shachar Shemesh
Shachar Shemesh

Reputation: 8563

I've got two answers for you.

The first answer is "don't do it". There is, almost certainly, a better way. You can specify to sudo that certain users can perform certain commands without entering a password. In all likelihood, that is what you want to do.

Having failed to convince you, however, I will let you in on a little secret. sshpass works on sudo, so:

sshpass -p 'my password' sudo -S su -c some-user ./some_command

Of course, while there, we can cut the su middle man:

sshpass -p 'my password' sudo -S -u some-user ./some_command

Upvotes: 3

Related Questions