On Friday afternoon I was asked to whip up a way of calling a command on a unix box by just bringing up a URL in a browser (insecure, I know, but it's what the customer insisted they wanted. Whoever said the customer is always right obviously wasn't talking about IT consulting. :) ).
There were a couple of extra issues. Firstly, the command takes arguments that had to be passed through the URL. Secondly, the command had to be run as a specific user. The first requirement is not so complicated, all web languages provide easy access to URL variables. However the second requirement was a little more puzzling.
My initial approach was to think of the problem as a regular Unix problem. If you have to execute a command or a series of commands, you write a shell script. So I thought about writing a CGI shell script. This is my reasoning:
With the platform decided, I started by looking at how to get URL arguments into the script. Since I was a little short on time, I didn't want to start looking up how CGI worked, which environment variables were set, etc. A quick Google search turned up bashlib, a great little project designed to make using Bash as a CGI scripting tool easier, specifically by handling things like URL variables. This made the first point given above trivial.
Now on to the second point, running the command as another user. Now I like to think I know a fair bit about Unix, but I'm mainly a developer and not a sysadmin, so although I had heard about Sudo I had never used it. It turned out to be exactly what I needed. At first I had tried just using su, but apart from being horribly insecure, I couldn't find a way of using it non-interactively. When that approach failed, I looked up sudo. All I needed was a single line in /etc/sudoers with the command, the calling user and the user the command should be called as. It's important to include the directive NOPASSWD so that the command can be run in a script without expecting a password.
And that was it, problem solved! That's how I ended my work week. I like doing something different now and again, since it's easy to get burned out working week in week out on the same thing, especially in the "client is being a pain" phase. And it's the kind of task that allows you to learn new things in small steps and relatively stress-free.
Why have I called this post "Choosing the Right Tool"? I am referring to writing a CGI in Bash. When you have a problem like the one I have described, where I could have done it in PHP, Perl, Python or whatever, you have to look at the most elegant solution and that which satisfies the most "unnamed criteria" - things that don't usually go into a project description but are a given, like efficiency or maintainability, mentioned above. In this context, I think I made the right choice.
Posted by Dave at September 7, 2003 12:32 PM