Run sudo as specific user without password

10.7k views Asked by At

I used the following command in my script

sudo su - user -c bash <<EOF
cp /home/test.txt /opt/

EOF

If I use the sudo su - user on terminal, Unix don't ask me the Password but if I try to run the script the terminal ask me the Password and if I delete the EOF part the rest of code run when I quit the session. I want to run the command in user mode sudo but the terminal don't Need ask me the Password.

If I use

sudo su - user <<EOF

code

EOF

I have an error in .bash_profile: too many argument

4

There are 4 answers

1
SSD On

Then don't use sudo, then it won't ask for password, but you will to be have logged in as root!

2
ColOfAbRiX On

I guess you need to execute your command as a different user. This might be your answer: Run a shell script as another user that has no password

sudo -H -u otheruser bash -c 'echo "I am $USER, with uid $UID"' 

It is a quote from the link. Probably the following is better for you:

sudo -H -u otheruser bash <<EOF
cp /home/test.txt /opt/
EOF

UPDATE: You may wish to create a specific sudo rule to run a specific command without password (inside /etc/sudoers file -remember to use visudo to edit it-):

otheruser ALL=NOPASSWD: /full/path/to/your_command.sh

(of course you need root access to edit sudoers, I hope you can do it). And create the script called your_command.sh that contains your logic. You'll then be allowed to run it without password:

sudo -H -u otheruser your_command.sh

I know, it's not a "single line command" but it is safe as it allows only one specific command without password. And it doesn't require a password, of course!

16
Jahid On

I want to run the command in user mode sudo but the terminal don't Need ask me the Password.

The scenario you are experiencing is caused by the users cached credentials for sudo, which allow sudo to maintain a session and any further sudo command will not prompt for passwords.

Check this:

Open a new terminal and run sudo whatever, then close it and open another new terminal and run sudo whatever, you will see that sudo asks for password every time...

If you still need to do that, then you have the following options:

Prevent sudo to ask for password permanently:

run sudo visudo and look for the line root ALL=(ALL) ALL, then add a line

username ALL=(ALL) NOPASSWD: ALL 

then save and exit.

Note: This is a security risk

Or Prevent sudo to ask for password permanently only for specific script:

run sudo visudo and look for the line root ALL=(ALL) ALL, then add a line

username ALL=NOPASSWD: path_to_the_script

then save and exit

Provide password inside the script, by running your sudo command like this:

sudo -S <<< "password" command

Note: This is a security risk too.

0
Cori On

What worked for me was:

sudo passwd -d <username>

this command deleted the password for the specified user.