As we know that, password must be inputted while switching user [Username: test, Password: test]

[user1@hosts ~] $ su test
[test@hosts ~]$ 

Now I want to create a shell script (example: login.sh) to switch user without entering password.

My shell script is:

su - test
test   # The password of user test

But it still needs password entering.

How can the shell script accept the password? Thanks in advance!!

  • Have a look at this answer, in this case sudo is the tool you need. – Shadok Jan 28 '13 at 11:38
  • @Shadok That requires you to enter a password at some point. I guess the OP needs expect. – slhck Jan 28 '13 at 11:39
  • Thanks for @Shadok, but I don't think the answer is what I want. I just want to switch user by script, but execute command by another user. – Marslo Jan 28 '13 at 12:16
  • Hi @slhck , I have finished my problem by using ssh. However, I think expect is a good idea. I don't use that command before, but I will have a try. Thanks!! – Marslo Jan 28 '13 at 12:46

Actually, I found another method to switch the user without password (Even if the new user needs password authentication).

That is using ssh

Alias file in user1:

alias tt="ssh test@"

And cat the user1's id_rsa.pub to test's authorized_keys: user1:

  • user1: create ssh public key: rsa_id.pub

    $ ssh-keygen -t rsa

    press yes if asking...

  • upload the user1's public key to test's directory (this step needs input the password):

    $scp id_rsa.pub test@

  • add the rsa_id.pub into .ssh/authorized_keys

    $ su - test


    $ cd $ cat rsa_id.pub >> .ssh/authorized_keys

    $ chmod 644 .ssh/authorized_keys

Then switch user by using tt

$ tt
Last login: Mon Jan 28 20:27:34 2013 from localhost
[test@host ~]$
| improve this answer | |

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.