Files
jimeh.me-v3.0/source/blog/_posts/2010-02-22-built-in-sudo-for-ruby-command-line-tools.md
2010-02-24 13:07:16 +02:00

31 lines
1.6 KiB
Markdown

---
layout: post
title: Built-in Sudo for Ruby Command-Line Tools
categories: [technology, ruby, git, gist]
---
I was looking through [my gists][gists] today on GitHub, and decided I'd do a couple of posts on some of the pieces of code I've put up there. The first of which is the `sudome` Ruby method.
Ever written a command-line tool in Ruby that requires root access for one reason or another? The simplest way to achieve this is to have the end user call the command via `sudo`. It's not the most elegant solution there is, but it works.
A more elegant solution might be what the [Fink Project][fink] is doing with their `fink` command. It doesn't need to be run via `sudo`, as it calls it within itself. Meaning that when you run `fink`, you'll be prompted to type your password, just as if you had used `sudo`. Some might argue that this is not good practice, and they are probably right. But it all depends on the details of what you're doing.
A while back I was working on something which the best solution was to make sure the tool always runs as root. To get identical functionality as Fink, I wrote the very simple method shown below:
{% highlight ruby %}
def sudome
if ENV["USER"] != "root"
exec("sudo #{ENV['_']} #{ARGV.join(' ')}")
end
end
{% endhighlight %}
Simply call `sudome` as early as possible in your code. If needed it will re-run your script with `sudo`, requiring the user to type his password, at which point your script then has full root access to the system.
» [Original Gist on GitHub][gist]
[gists]: http://gist.github.com/jimeh
[fink]: http://www.finkproject.org/
[port]: http://www.macports.org/
[gist]: http://gist.github.com/239876