How to run a command with sudo from a certain path?

1

I'm setting up some automation with remote controlled bots. It's imperative that these bots have only exactly the permissions to run certain commands (I can't open the permissions too much in the sudoers to allow arbitrary commands).

It works well, I can setup the several commands I need and get around the password limitation (because there's no opportunity to type passwords when sudoing) with the NOPASSWD directive in the sudoers file. But there is a problem. Some scripts, notably those written in some... er, PHP frameworks... expect to be run from a certain directory, that is considered the root of the project.

This directory is owned by another user, www-data or apache most of the times. Ok, I can authorize the bot to run the script as this user, but I can't cd to the correct path in a non-interactive session, because it's not possible to include cd as a command in the sudoers file.

Normally what I would do is something like cd /var/www/path/to/app && php whatever.php --some args, but I can't find a way to setup this pattern in the sudoers file, it seems to not be possible.

Do you know a way to get around this?

Victor Schröder

Posted 2017-02-07T13:12:11.207

Reputation: 111

Answers

1

The only work around I know of would be to create a small shell script containing your code and then allow the user/bot to execute the script.

sudo cd /var/www/path/to/app && php whatever.php --some args

will not work because it is two commands, and sudo lets you run one. but if you put this in a small script (lets say /var/www/scripts/something/script.sh):

#!/bin/bash
cd /var/www/path/to/app && php whatever.php --some args

You can run it using

sudo /var/www/scripts/something/script.sh

nStensen

Posted 2017-02-07T13:12:11.207

Reputation: 111