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

Hi everyone:

I have a big trouble, 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 sudo, I've tried everything but seems su doesn't accept input redirection, please help me, it's very urgent

Thanks in advance

Try this

sudo -u John /path/to/command

That will execute the command as the specified user, just replace John with the user's short name.

my user isn't in sudoers and I don't have root access

have your script run as root, and it doesn't need to be.

sudo myscript.sh, and then in the script have it execute said commands as those users via sudo -u <username>

thanks for your response but my user doesn't have permissions for sudo, my account is very restricted.

Could you post the su command you tried with the attempted redirections?

#!/bin/bash
su - user2<< EOF
pass
/home/user2/check_mail $HOME
EOF

If you have the second user's password then you could write an expect script, but I wouldn't recommend it since you would have to hardcode their password in the script. It might look something like this:

#!/usr/local/bin/expect

set userpass "their_password"

send "su - login_name"
expect "Password:"
send "$userpass\r"
send "command1\n"
send "command2\n"
send "exit\r"
expect eof

Redirections aren't supposed to work with su. It will try and skip straight to a terminal device to prevent people trying shenanigans. Something more sophisticated like expect is needed to fool it.

And fooling it it is, since it's demanding interactive authentication for a reason. An expect script to cram a keyboard-authenticated password into a shell script is a very bad idea, anyone who sees the script will have the password. If you need permissions you haven't got, you should contact your sysadmin and get them.