How to switch user in shell scripting (without root)?

Hi everyone:

I need create a script that must switch user and then must execute
certain commands, sadly neither my user nor the second user have no privileges
for su - ,

I've tried everything but seems su doesn't accept input redirection,

please help me,

#!/usr/local/bin/expect

set userpass "mypassword"

send "su - myuser012"
expect "Password:"
send "$userpass\r"
expect eof

after run script this error

./autos.sh: line 7: send: command not found
./autos.sh: line 8: expect: command not found
./autos.sh: line 9: send: command not found
./autosl.sh: line 10: expect: command not found

My os = SunOS

Hello :slight_smile:

1)
Lets have a look if expect is installed, and if so, where it exactly is.

which expect

2)
expect is not bash (or ksh,zsh,sh)!

3)
How did you start the script?
If expect is installed, but you started the expect script using bash or sh, then the script is executed as such (bash/sh).

Greets

EDIT:
4)
Either way (expect or (any) shell), the user has to type the password.
Or you should switch to credential files.

hth

The sudo tool is designed to give you the choice and it is probably the best way.

Incidentally, you should not really try to force the password in like this. If you have a process to run that is automated, i.e. you don't fire it off as a real person on the command line, then you should really run it as a non-personal account. You can then give that account the sudo privilege to not require a password.

The problem is that if you script this, then anyone able to read your script will know the account password. Additionally, good practice would have you changing the passwords regularly and that might require editing every script each time.

How far have you got with this now?

Kind regards,
Robin

can you do this using

 chmod +s script

and then change the owner of the script to the second user.

I am not sure but there should be spawn to call command

#!/usr/local/bin/expect
spawn su -
expect "Password:" { send "passwd\r" }
expect "# " { send "uname -a\r" }
expect "# " { send "pwd\r" }
expect "# " { send "q" }
exit

Another way is :
Check if you have SSH or telnet to the server available. you can telnet or ssh to server. You could use other user.

Also I use

while writing script. Please check man pages before you start.