Monday, January 23, 2006

Ruby for system admin (1)

Few months back I came across Python for system administration works. It's kinda cool to see OO stuff used in system admin works but Python is really not my cup of tea.

So why not Ruby? Well here is the equivalent script in Ruby.

#!/usr/bin/env ruby

File.open("/etc/passwd").each { |line|
next if line.match(/^#/)
uname, xpass, uid, gid, junk, home, junk2 = line.split(":")
next if uname == 'root' or uname == 'nobody' or uname[0,2] == 'uu'
next if uid.to_i <= 100 and uid.to_i > 0

if uid.to_i == 0 and uname != 'root'
puts "WARNING: UID=0 #{uname}"
elsif xpass != '!' and xpass != '*' and xpass != 'x'
puts "WARNING: Check password #{xpass}"
end

if home != "/" and FileTest.exist?(home) and File.stat(home).directory?
home_size = `du -s -k -0 #{home} 2>/dev/null`.split("\t")[0]

if home_size.nil?
home_size = "unknown"
else
home_size = home_size + "k"
end
else
home_size = "skipped"
end
printf("%-18s %-17s %10s %-9s\n", uname, uid, home, home_size)
}

I timed both of the scripts and here are the result:


sey@babyunix:~$ time python test.py
Disk
Username (UID) Home Directory Space Security
------------------------------------------------------------
dhcp (101) /nonexistent skipped
syslog (102) /home/syslog skipped
klog (103) /home/klog skipped
sey (1000) /home/sey 7708040K
fetchmail (104) /var/run/fetchmail unknown
messagebus (105) /var/run/dbus 4K
hal (111) /var/run/hal 4K
saned (112) /home/saned skipped
gdm (106) /var/lib/gdm unknown
hplip (107) /var/run/hplip 16K
mysql (108) /var/lib/mysql 20629K
postfix (109) /var/spool/postfix 209K
sshd (110) /var/run/sshd 0K
ntop (117) /var/lib/ntop unknown
postgres (118) /var/lib/postgresql 4K

real 0m3.004s
user 0m0.248s
sys 0m0.728s


sey@babyunix:~$ time ruby test.rb
dhcp 101 /nonexistent skipped
syslog 102 /home/syslog skipped
klog 103 /home/klog skipped
sey 1000 /home/sey 7708040k
fetchmail 104 /var/run/fetchmail unknown
messagebus 105 /var/run/dbus 4k
hal 111 /var/run/hal 4k
saned 112 /home/saned skipped
gdm 106 /var/lib/gdm unknown
hplip 107 /var/run/hplip 16k
mysql 108 /var/lib/mysql 20629k
postfix 109 /var/spool/postfix 209k
sshd 110 /var/run/sshd 0k
ntop 117 /var/lib/ntop unknown
postgres 118 /var/lib/postgresql 4k

real 0m2.890s
user 0m0.245s
sys 0m0.718s

Ruby is slighty faster here but it's insignificant. In terms of code comprehension, both are very similar, and both got the job done.
Feedbacks welcomed.

No comments: