Pergunta

I'm trying to create a post install script for Linux and I want to have the script edit the sudoers file so that users wont need to do sudo visudo and edit it manually.

In the script I have:

if [[ ! `sudo -l -U "$user" 2>&1 | grep "ALL"` ]]; then
    su -c "echo '$user ALL=(ALL) ALL' >> /etc/sudoers"
    su -c "echo '$user ALL=(ALL) NOPASSWD:ALL' >> /etc/sudoers"
fi

the problem with this is that when I sudo whoami after I run the script I get this output:

sudo: >>> /etc/sudoers: syntax error near line 31 <<< sudo: parse error in /etc/sudoers near line 31 sudo: no valid sudoers sources found, quitting sudo: unable to initialize policy plugin

How do I do this without ruining my sudoers file?

EDIT: As requested here is my sudoers file:

Defaults    env_reset
Defaults    mail_badpass
Defaults    secure_path="/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"

# Host alias specification

# User alias specification

# Cmnd alias specification

# User privilege specification
root    ALL=(ALL:ALL) ALL

# Members of the admin group may gain root privileges
%admin ALL=(ALL) ALL

# Allow members of group sudo to execute any command
%sudo   ALL=(ALL:ALL) ALL

# See sudoers(5) for more information on "#include" directives:

#includedir /etc/sudoers.d

Mind that it is not possible to do cat /etc/sudoers after the script has run.

EDIT 2: The solution is to define $user as user=$(whoami)

Foi útil?

Solução 2

My solution is to have the script ask the user to enter his password and store the value in a variable to be used along with Expect. The script installs Expect if it's not installed and then the script does:

read -p "Please enter your password: " PASSWD
export PASSWD
username=$USER
export username

if [[ ! `sudo -l -U "$USER" 2>&1 | grep "ALL"` ]]; then
  expect -c '
      spawn "su -c \"cat <<EOF >> /etc/sudoers.d/$env(username)
          $env(username) ALL=(ALL:ALL) ALL
          $env(username) ALL=(ALL) NOPASSWD:ALL
EOF
\"
      "
      expect "Password:\r"
      send $env(PASSWD)
      interact
  '
fi

Outras dicas

As the comment at the end of the default sudoers file suggests, you should create a new file in /etc/sudoers.d/.

Doing this from a (Debian) package's postinst seems fishy, though. Where does the value of user come from?

Also, any particular reason this user is not simply added to one of the existing groups, admin or sudoers?

You can edit file /etc/sudoers through "pkexec visudo", after when you will delete bad line, sudo will be work.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top