Is there a way to pass su password via script to connect to SSH?

Hi to all,

How can I send the password automatically within the script below when I try to switch to su ?

Currently I'm able to login via ssh to hostname entering automatically the ssh password using sshpass but in the process requests me the su password

# sshpass -p 'ssh_password' ssh myuser@$hostname "su -c \"cd /some/path/ && ls -l\""
You are trying to access a restricted zone. Only Authorized Users allowed.
Password:

I've tried something like this,but is not working.

sshpass -p 'ssh_password' ssh myuser@$hostname "su myuser su_password -c \"cd /documents/backups/ && ls\""

Below I show 3 ways I've tested and only 3rd accepts the su_password , the other 2 requests password and when I enter it, answers with su: incorrect password

1-) Trying with username and su_password (FAILS)

# sshpass -p $ssh_password ssh -t $myuser@$hostname "su $myuser 'MysuPassword123' -c \"cd /some/path/ && ls\""
You are trying to access a restricted zone. Only Authorized Users allowed.
Password:
su: incorrect password
Connection to AAA.BBB.CCC.DDD closed.

2-) Trying only with username (FAILS)

# sshpass -p $ssh_password ssh -t $myuser@$hostname "su $myuser -c \"cd /some/path/ && ls\""
You are trying to access a restricted zone. Only Authorized Users allowed.
Password:
su: incorrect password
Connection to AAA.BBB.CCC.DDD closed.

3-) Trying only with su without username/su_password (Success)

# sshpass -p $ssh_password ssh -t $myuser@$hostname "su -c \"cd /some/path/ && ls\""
You are trying to access a restricted zone. Only Authorized Users allowed.
Password:
docs file1 file2
Connection to AAA.BBB.CCC.DDD closed.

I already asked this here without answer yet.

How can I do this? Thanks in advance.

Why do you use su into $myuser after you logged in with $myuser ?
You are already $myuser on that box, so you do not need su to execute commands.

Please correct me if i got something wrong ?

Regards
Peasant.

Hi, @Peasant

I need to send su after I'm logged in, since if I don't do that, I cannot send commands like cd, ls, cp etc.

You would be better with a sudo rule to permit you to perform the necessary action without a password being required. A sensible way is to have a specific script you may run but not edit to prevent unauthorised use.

Would that help?
Robin

2 Likes