How to Execute Commands as Another User Without Password Using Sudo


4 views

When managing Linux servers, you might encounter situations where you need to execute commands as another user while being logged in as root (or another privileged account). The sudo -u command provides this capability:

sudo -u username command-to-execute

In your specific case with Drupal and Aegir, you can restart Apache as the aegir user without knowing their password:

sudo -u aegir apache2ctl graceful

For this to work, your sudoers file (/etc/sudoers) needs proper configuration. Check if the root user has unrestricted access or if specific rules exist for the aegir user:

# /etc/sudoers example
root    ALL=(ALL:ALL) ALL
%aegir  ALL=(ALL) NOPASSWD: /usr/sbin/apache2ctl

Before executing commands, verify what privileges your account has:

sudo -l -U aegir

If sudo isn't configured properly, you can use su with the -c flag (requires root privileges):

su - aegir -c "apache2ctl graceful"

While powerful, these methods should be used carefully:

  • Limit sudo access to specific commands
  • Regularly audit sudoers file
  • Consider using command aliases for complex operations

If you encounter "user not in sudoers file" errors:

visudo
# Add your user to the file with appropriate permissions


When administering systems with multiple service accounts like Aegir in Drupal environments, we often need to execute privileged commands while maintaining proper process ownership. The standard sudo -u username command approach fails when the target user's password is unknown - a common scenario with automated provisioning systems.

While sudo -u aegir apachectl restart seems logical, it prompts for Aegir's password by default. This creates a chicken-and-egg problem for root users managing service accounts.

# This will fail if you don't know aegir's password
sudo -u aegir apachectl graceful

The solution lies in configuring /etc/sudoers to allow passwordless execution. For Aegir specifically:

# /etc/sudoers.d/aegir_apache
Cmnd_Alias APACHE_CTL = /usr/sbin/apachectl, /usr/sbin/service apache2 *
aegir ALL=(root) NOPASSWD: APACHE_CTL
%admin ALL=(aegir) NOPASSWD: ALL

1. Create the sudoers configuration file:

sudo visudo -f /etc/sudoers.d/aegir_apache

2. Verify the syntax:

sudo visudo -c

3. Execute commands as Aegir:

# As root user
sudo -u aegir sudo apachectl restart

# Alternative approach (Debian/Ubuntu)
sudo -u aegir sudo service apache2 reload

When configuring such access:

  • Restrict commands to only necessary binaries
  • Regularly audit sudoers files
  • Consider using SELinux/AppArmor for additional protection
  • Document all exceptions in your change management system

For systems using PolicyKit (common on modern Linux distros):

# /etc/polkit-1/localauthority/50-local.d/aegir-apache.pkla
[Apache Restart Privileges]
Identity=unix-user:aegir
Action=org.freedesktop.systemd1.manage-units
ResultAny=yes