Nomad
Nomad

Reputation: 1139

how can i switch user in shell script by using sudo and password

I'm working on a script in which I need to change the user, i have sudo access, i tried something like below but without success.

echo $passwd | sudo -S su - oracle

I even tried installed ssshpass but no success with that either. Is that even possible or do I need to install something else to make this work?

Any idea

Upvotes: 1

Views: 3883

Answers (1)

Joao  Vitorino
Joao Vitorino

Reputation: 3256

If you will run your script with root account, you can just

message="The cake is a lie"
su username -c 'echo $message'

If you will run your script with another user you have two ways to do that,

1) Configuring pam like bellow so when you run su user2 -c 'command' logged with user1, linux will not ask for password.

Add the following lines right below the pam_rootok.so line in your /etc/pam.d/su:

auth       [success=ignore default=1] pam_succeed_if.so user = user2
auth       sufficient   pam_succeed_if.so use_uid user = user1

The first line makes sure the target user is user2. If it is, the next line will take control and succeed authorization if the calling user is user1.

If the target user is something else, the second line will be ignored and the usual authentication steps will be performed.

2) Write your script using expect as here

Upvotes: 2

Related Questions