I want to run

  • a shell script restore
  • as postgres user
  • from php script (the user name is php)
  • using sudo (so password is not required)

the script will have few lines of code, something like

dropdb <database name>
psql -c "create database <database name> with encoding 'unicode';" -U edutemplate1
psql -d <database name> -f edu.hourly.sql 
  • what would be the sudo command syntax to run the script restore
  • what would be the sudoers syntax to allow php user to run restore script as postgres user?

  • Sudo version 1.7.2p7

  • Linux testing 2.6.34-12-desktop #1 SMP PREEMPT 2010-06-29 02:39:08 +0200 x86_64 x86_64 x86_64 GNU/Linux


the first part of the question was already answered on SO sudoers-syntax-to-run-shell-script-as-php-user


I added php ALL=(postgres) NOPASSWD: /usr/bin/id to /etc/sudoers and then did su php and then sudo -su postgres /usr/bin/id but I am asked for postgres' password. If I issue the same sudo command under the user root I will get correct output 'uid=26(postgres) gid=26(postgres) groups=26(postgres)'


updating sudoers to php ALL=(postgres) NOPASSWD: ALL makes it work ...

  • 1
    You want sudo -u postgres /usr/bin/id, not -su. – Bill Weiss Mar 28 '11 at 23:38

See also this answer for a similar scenario.

This goes in /etc/sudoers:

php ALL=(postgres) NOPASSWD: /the/restore/script

And you make php issue a command like this: sudo -u postgres /the/restore/script


You can do it from root "su $USERNAME -c "command"" anyway you can do it VIA sudo as well, if You can please describe what You wanna do exactly? For example from which user? is it require password? (you can define it in /etc/sudoers) By "php user" You mean www-data, or nobody or other user?

  • I need to run restore shell script from my php script. The php user's name is php. So I guess I need to sudo to run the 'restore' script as different user than 'php' user. I do not know what would be the sudoers syntaxt to I can call exec("sudo -su postgres -S '/scripts/restore'", $output); from my php script – Radek Mar 28 '11 at 5:28
  • exec("sudo -su php...."); But by default sudo will ask for the password for the account that You wanna use, so You can use some "expect" script first ;) – Ryszard Stawiarski Mar 28 '11 at 5:33
  • I don't know what some "expect" script first means. What I understood is that I can use sudo without password if the correct line is in sudoers. The question I asked here is how the line should look like so I can use sudo without the password... – Radek Mar 28 '11 at 5:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.