0

I want to log in to user2 via bash script, so my script contains:

sudo -i -u user2

Also I don't want to enter my sudo password by hands. Before I did something like this:

echo "my_sudo_password" | sudo -S <command> 

but if I am trying it in this case:

echo "my_sudo_password" | sudo -S -i -u user2

I have error

-sh: 1: my_sudo_password: not found

Can you answer what am I doing wrong?

Leo
  • 1
  • Rather than hardcode the password somewhere, you can add the script to sudoers. This will allow just this script to run without the password requirement – matigo Mar 26 '22 at 12:16
  • This is really not the intended way to use sudo and is not secure. Hardcoding passwords is a very bad idea. This doesn't work because sudo intentionally prevents it from working. – user10489 Mar 26 '22 at 13:19
  • 1
    I suspect what's happening here is that your credentials are already cached, so sudo is not asking for your password, and the "unused" stdin is getting passed to user2's login shell (as if you'd done echo "my_sudo_password" | sh -l) – steeldriver Mar 26 '22 at 15:05
  • @matigo I have a Go CLI tool. When user run this tool it runs some bash commands. If I add that bash commands in sudoers, user will be able to use it manually, but I don't want that. What I need to do in this situation? For now, the only option that I've invented is hardcode the sudo password and run sudo without caching any creds :( – Leo Mar 26 '22 at 16:07

1 Answers1

0

If lack of security doesn't bother you, you can try this:

coproc ( sleep 2; xdotool key your_password key Return )
sudo -i -u user2

which simulates your doing it by hand. The sleep wait time can be adjusted to suit your situation.

user985675
  • 151
  • 4