-1

I wanted to write a script to add some tools to my VPS or VMS and I write something like that

# Edit sudoers
echo -e "${GREEN}Configure sudoers...${NOCOLOR}"
echo
echo '# Allow user to use sudo without passwd' >> /etc/sudoers
echo '$USER ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers

this script run as Sudo and i test echo $USER in Sudo is the user name, not root I mean I'm kind of new so I did not know that and write this but when I test it I'm getting error permission error i don't know what to do I did some search but can't find anything

2 Answers2

1

I have three things to point out there. One, you should really use visudo to edit the /etc/sudoers file, even if you set $EDITOR to a script that echoes that content. The other is that it is sub-optimal to let any user run any command without a password. Finally, $USER will equal root, so that will be pointless.

If you really want to do that, make a separate script that has this in it:

echo '# Allow user to use sudo without a password' >> $1
echo "$PERSON ALL=\(ALL\) NOPASSWD:ALL" >> $1

Second, make yet another script that runs your main script like this:

sudo "env PERSON=$USER /your/script/here"

That should tidy it up a bit, because you can be sure that the whole script is being run as root, and visudo keeps backups in case you screw up the sudoers file.

Garo
  • 2,059
  • 11
  • 16
kettle
  • 226
  • 1
    Or, rather than editing the sudoers file directly, create a separate file per user that just contains that line: echo "$USER ALL=(ALL) NOPASSWD:ALL" > /etc/sudoers.d/$USER. – berndbausch Apr 01 '21 at 05:32
  • That's also a good idea. The point of visudo is just not irreversibly screwing up the main file. – kettle Apr 01 '21 at 05:41
0

Instead of using:

sudo echo "# This is a comment" >> someFile.txt

You can use:

echo "# This is a comment" | sudo tee -a someFile.txt

NOTE: Don't forget the -a flag for the tee command, otherwise you will end up overwriting the whole file with the new comment line.

Read more about tee here:

nltc
  • 16