Official website for Linux User & Developer
FOLLOW US ON:
Jul
19

Ruby development for system administrators

by Koen Vervloesem

Koen Vervloesem doesn’t like shell scripts that are difficult to maintain, therefore he uses Ruby for his sysadmin tasks. Do the same with his four-page guide…

The function ‘collect’ invokes the function 2*n for each element n in the array numbers. As a result, ‘doubles’ has the content [2, 4, 6, 8, 10]. Most of the built-in Ruby classes such as Array have some methods that use a code block as a parameter, especially for looping, iterating, sorting and mapping. Once you get used to code blocks, they make programming in Ruby quite intuitive. For example, it comes in handy when querying a database:

#!/usr/bin/env ruby
require ‘mysql’
db = Mysql.new(“localhost”, “root”, “password”)
db.select_db(“myusers”)
result = db.query(“select name,email from users”)
result.each { |row| puts “User #{name} has email address #{email}” }

In the first line, we set the #! line that allows the script to be executed by the shell if the file is executable. With the ‘require’ line, we indicate that we use the MySQL module (which we have first to install separately with our operating system’s package manager).

Other features will be familiar from other programming languages or even shell scripts: for example, running external commands with a backtick or regular expressions. This is how you use both features to handle an unknown host:

resolve = `host #{address}`
puts “Host #{address} does not exist” if resolve =~ /does not exist/

The value of the variable ‘resolve’ is set to the output of the shell command ‘host address’. This value is then compared to the regular expression ‘does not exist’ (which is the output of the host command on a Linux system; adapt this if you use another operating system). If it matches, a message is shown.

Text processing
Ruby has great capabilities to process text, which is an important task in many UNIX workflows. The String class is a powerful instrument for this: it can hold, compare and manipulate textual data. Let’s show how we open a CSV (comma-separated values) file with bandwidth data of an OpenWrt router and filter the download data for a specific host on each day:

#!/usr/bin/env ruby
require ‘csv’
ip = ARGV[0]
CSV::Reader.parse(File.open(‘bandwidth.csv’)) do |row|
if row[0].to_s == “download” and row[1].to_s == “day” and row[3].to_s == ip
   puts “From #{Time.at(row[4].to_i)} to #{Time.at(row[5].to_i)}: #{row[6].to_i/1048576} Mbytes”
   end
end

This script uses the csv library, where we use the Reader.parse method to read the rows of the CSV file. The parse method uses a code block (here inside a do-end block instead of inside brackets, but this is the same), which is executed for each row. The elements in a CSV row are now elements in the row array. We test for the right requirements (the row should be about daily download data for the specific IP address), where we convert the row elements to strings, and then we show a message for each match: the begin and end time of the day (the row has the time in seconds, so we convert the row element to an integer and then use the Time.at method to convert it to a human-readable form), and then the number of megabytes downloaded. In the beginning, we set the value of the variable ‘ip’ to ARGV[0], which is the first argument that the user assigns to the program on the command line.

Pages: 1 2 3 4
  • Tell a Friend
  • Follow our Twitter to find out about all the latest Linux news, reviews, previews, interviews, features and a whole more.

    5 Comments »

    • Dummy00001 said:

      The guide is quite informative.

      But since your site engine does not support proper code formatting, examples require tweaking before use.

      Or Ruby’s really capable of interpreting the WinWord-style single quotes – “require ‘csv’”?

    • Ruben Espadas said:

      Nice introduction, the said “when men were men….” is forgotten, but the tools help more than “prestige”. Thanks for this article.

    • Matthew Closson said:

      @Dummy00001 Ruby can use single or double quoted strings. Double quoted strings give you some extra functionality when it comes to string interpolation but it is a fairly standard Ruby practice to use single quoted otherwise.

    Trackbacks

    What's your opinion?

    Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

    Be nice. Keep it clean. Stay on topic. No spam.

    * Required fields