Tutorial on system administration using Ruby scripting _ruby topics

Source: Internet
Author: User
Tags wrapper ssh ruby on rails

Brief introduction

Ruby is an extremely rich, free, simple, extensible, portable, object-oriented scripting language. Recently, it has been widely popular in the Web field. This is partly due to the very powerful WEB application development Framework Rails,rails is written in Ruby. Rails, also known as Ruby on Rails (ROR), as the name suggests, provides a very powerful platform for fast and effective development of WEB applications. It is highly scalable and there are many sites on the Web that are built with Ruby on Rails.

In addition to being used as a WEB application development platform with Rails, Ruby has the other side that is less mentioned, as a powerful scripting language, like Python or Perl. It has a very powerful function, because it can use a lot of built-in and external libraries, so you can use its power to solve the common system management work environment, many of the requirements of scripting programming.

System management requires a lot of scripting to make things simpler and more efficient. Writing scripts can better address user management, process management, file management, package management, and other basic automation requirements than tedious manual work. In this scenario, Ruby is very useful. It has a very good library to meet this point.

For this article, I assume that the reader has the application knowledge of Ruby. The basic examples provided here use pure Ruby, so can any UNIX-like support in Ruby? System and Windows? Run on. For more advanced Cfruby examples, you need to be able to use a UNIX system. All of the following examples are already in a Linux? The machine was tested using Ruby v1.8.4. They should also be available for the latest version of Ruby.

Ruby in practice

The first example searches the specified path for files that match a given pattern and gives detailed information about those files in a user-friendly manner. Implementing this goal does not depend on any command-line utilities, just using Ruby's built-in APIs. Therefore, this example can be run on any platform with Ruby running.

Also, this example shows how powerful Ruby is in simplifying scripting requirements. Rather than simply simulating the *nix "find" command, it is built on top of the command, and thus has a strong customization capability when using Ruby.
Listing 1. Searches for files in a given path that match patterns in a given pattern, and displays their details

Require ' find ' puts "puts"-----------------------File Search-----------------------------------"puts" "print" Enter The search path: "SearchPath = gets SearchPath = Searchpath.chomp puts" "Print" Enter the search pattern: "pattern = gets pattern = Pattern.chomp puts "----------------------------------------------------------------------" puts " Searching in "+ SearchPath +" for the files matching pattern "+ pattern puts"----------------------------------------------
  ------------------------"puts" "Find.find (SearchPath) do |path| If Filetest.directory?
    (path) if File.basename (path) [0] = =?
   Find.prune # Don ' t look any further to this directory. 
    Else Next end else if File.fnmatch (pattern,file.basename (path)) puts "Filename:" + file.basename (PATH) s = sprintf ("%o", File.stat (Path). Mode) print "Permissions: puts s print" Owning UID: "Puts File . Stat (path). UID print "Owning GID:" puts file.stat (path). UID PRint "Size (bytes):" Puts File.stat (path). Size puts "---------------------------------------------------" end

 End End

In this example:

    • 第5-11 line-Requests the user to provide a search path and search pattern.
    • Line 16th-Use the Find method in Ruby to traverse the specified search path.
    • Line 17th-Check if the found file is a directory. If it is a directory, and it is not ".", it iterates through the directory recursively.
    • Line 24th-Use the "Fnmatch" method in the "File" class to check whether the found file conforms to the given pattern.
    • 第25-34 line-Prints the file details if the file conforms to mode.

Here is a sample output for this script.
Listing 2. Example output for the first example

[root@logan]# Ruby findexample.rb

-----------------------File Search-----------------------------------

Enter the search path  :/test

Enter the search pattern: *.rb
--------------------------------------------- -------------------------
searching in/test for the files matching pattern
*.rb-------------------------------- --------------------------------------

Filename   : s.rb
permissions:100644
owning uid  : 1
owning GID  : 1
Size (bytes):
---------------------------------------------------
Filename   : test.rb
permissions:100644
owning uid  : 0
owning gid  : 0
Size (bytes): 996
---------------------------------------------------
Filename   : s1.rb
permissions:100644
owning UID:  1
owning gid  : 1
Size (bytes):
-------------------------------------- -------------

One of the most common requirements during system administration is the efficient use of ZIP files to manage backups, or the transfer of a group of files from one computer to another. Ruby has a great advantage in this respect. The second example here is built on the first example, but includes a scenario in which the searched files need to be packaged into a zip file.

The built-in zlib module helps with gzip files, which is good for most cases. However, here I will use another good Ruby library, "Rubyzip", to create and process zip archives. Check the Resources section to find a link to download it. Also note that this example uses pure Ruby, which does not depend on any command-line utilities currently available on the computer.

Install Rubyzip

Download the "Rubyzip" gem from the link provided and copy it to the system. (at the time of writing this article, its filename is "Rubyzip-0.9.1.gem").
Run Gem installation Rubyzip-0.9.1.gem

Listing 3. Working with ZIP files

Require ' rubygems ' require_gem ' rubyzip ' require ' find ' require ' zip/zip ' puts ' "puts"------------------File Search D Zip-----------------------------"puts" "print" Enter The search path: "SearchPath = gets SearchPath = searchpath.ch OMP puts "print" Enter the search pattern: "pattern = gets pattern = Pattern.chomp puts"------------------------------ ----------------------------------------"puts" searching in "+ SearchPath +" For files matching pattern "+ pattern put S "----------------------------------------------------------------------" "puts" "puts"-------------------------- --------------------------------------------"puts" zipping up the found files ... "puts"-----------------------------
 -----------------------------------------"Zip::zipfile.open" ("Test.zip", zip::zipfile::create) {|zipfile|
 Find.find (SearchPath) do |path| If Filetest.directory?
    (path) if File.basename (path) [0] = =?
   Find.prune # Don ' t look any further to this directory.
   Else Next end else if File.fnmatch (pattern,file.basename (path)) p File.basename (path) Zipfile.add (Fil

 E.basename (path), path) end end}

This script creates a zip file named "Test.zip" for files that are searched based on the provided search path and search pattern.

This example does the following things:

    • 第9-15 line-Requests the user to provide a search path and search pattern.
    • Line 23rd-Create a new zipfile named "Test.zip".
    • Line 25th-Use the Find method in Ruby to traverse the specified search path.
    • Line 26th-Check if the found file is a directory. If it is a directory, and it is not ".", it iterates through the directory recursively.
    • Line 33rd-Use the "Fnmatch" method in the "File" class to check whether the found file conforms to the given pattern.
    • Line 35th-Adds the compliant files to the ZIP archive.

Here is a sample output:
Listing 4. Example output for the second example

[root@logan]# Ruby zipexample.rb

-----------------------File Search-----------------------------------

Enter the search path  :/test

Enter the search pattern: *.rb
--------------------------------------------- -------------------------
searching in/test for the files matching pattern
*.rb-------------------------------- --------------------------------------

-------------------------------------------------------------------- --Zipping up the
found files
... ----------------------------------------------------------------------"
s.rb" "
test.rb" "
s1.rb"

[root@logan]# unzip-l test.zip
Archive:test.zip
 Length   Date  Name
 --------  ----  ----  ----
   996 09-25-08 21:01 test.rb 09-25-08 21:01 s.rb-09-25-08 21:01
 --------          -------
  1092          3 files

Cfruby-Advanced System Management

According to the definition of the Cfruby site, "Cfruby allows for system administration using Ruby." It is both a Ruby function library for system management and a class Cfengine clone (actually a specific domain language for system management, or DSL).

Cfruby is basically a two-part package:

    1. cfrubylib– a pure Ruby library that contains classes and methods for system administration. This includes file copying, lookup, checksum checking, package management, user management, and so on.
    2. cfenjin– a simple scripting language that helps you write scripts for system administration tasks (you don't have to know Ruby).

Cfruby can be downloaded as a Ruby gem or tar compressed file. Gems are the easiest and easiest way to do it. Get the gem and install it using the "gem Install" command.

Install Cfruby:

    • Copy the downloaded Cfruby gem file to the system. (at the time of writing this article, its filename is "Cfruby-1.01.gem").
    • Run Gem installation Cfruby-1.01.gem.

Cfruby should now be installed on the system.
using Cfruby

Now, I'm going to show Cfruby's capabilities and how it simplifies system management dramatically.

There are two basic ways to access the functionality provided by the Cfruby library:

    1. Use the Ruby class directly in Libcfgruby.
    2. Using the Cfrubyscript wrapper, it provides a more concise interface for Libcfruby.

Direct use of Ruby classes in Libcfruby

Libcfruby is the core of Cfruby, which contains a set of modules that provide a variety of functions to simplify system maintenance and setup. To use Libcfruby, you need to add "Require_gem ' Cfruby" to the top of the script after you install the Cfruby gem. This allows you to directly access all the core modules in the Libcfruby, and you can use them as you want in the script as needed. The only disadvantage of this approach is that the Libcfruby is large, and it puts all the classes and methods into their respective namespaces. So, in order to access any one class, you need to qualify it with a namespace. For example, Libcfruby provides a way to obtain a system type. To get the type of operating system, you need to do the following:
Listing 5. Using Libcfruby to get the operating system type

Require ' RubyGems '

require_gem ' cfruby '

os = Cfruby::os::osfactory.new.get_os ()

puts (os.name)

This just gets the name of the operating system. As you do more with Libcfruby, your script will be flooded with more statements that specify namespaces. It is for this reason that another method of using Cfruby is very convenient.
Using the Cfrubyscript wrapper, this wrapper provides a more concise interface for Libcfruby

In order to use the Cfrubyscript wrapper, you need to add:
Listing 6. Using Cfrubyscript

Require ' RubyGems '

require_gem ' cfruby ' require ' libcfruby/cfrubyscript '



This will include Cfrubyscript in the script, and then you can access the Libcfruby functionality through a simpler interface.

Cfrubyscript did the following:

    • It exports a set of variables to the global namespace, such as $os, $pkg, $user, $proc, and $sched.
    • It puts most of the main modules into the primary namespace, so you can call Fileedit.set instead of Cfruby::fileedit.set.
    • It adds a number of helper methods for String and Array that can do some Cfruby things (Setup, edit files, and so on).
    • It also provides a good logger.

Therefore, you no longer need to specify a large heap of namespaces in the script. The example above for getting the operating system type now becomes this:
Listing 7. Using Cfrubyscript to get the type of operating system

Require ' rubygems ' require_gem ' cfruby ' require ' libcfruby/cfrubyscript ' puts

($os. Name)

This can be translated into a separate call, which uses the global variable $os. Cfruby is really powerful, it provides a lot of functions for the management class *nix system.

Now look at some of these features and some basic examples of how to use them.
User Management

In System management, one of the most common and most important tasks is the management of users and groups. Cfruby provides a powerful way to implement this task in a portable, simple way.

The task is implemented using the Usermanager object, which can be obtained from the OS module as follows.
Listing 8. Using Libcfruby to get Usermanager objects

Require ' RubyGems '

require_gem ' cfruby '

osfactory = cfruby::os::osfactory.new ()

OS = Osfactory.get_os ()

usermgr = Os.get_user_manager ()

If you use the Cfrubyscript method, there is already a global user management object, the $user, that can be used directly to invoke the method. I will use this method because it is simpler and easier to read.

The following shows how to use it to create and delete a user.
Listing 9. Using Cfgrubyscript for user management

Require ' RubyGems '

require_gem ' cfruby ' require ' libcfruby/cfrubyscript '

$user. AddUser (' Newusername ', ' Password ')

$user. DeleteUser (' Usernametodelete ', true)

What does the above code do?

    • Lines 1th and 2 – as usual, include Libcfruby and Cfrubyscript in the script.
    • Line 3rd – Create a new user with the password specified by the username "Newusername" and the second parameter.
    • Line 4th – Delete the user named "Usernametodelete". The value of the second parameter can be true or false to specify whether to delete the home directory of the deleted user.

Similarly, group operations can be done using the AddGroup () and DeleteGroup () methods in the Usermanager object.
Process Management

Another important task for administrators is to keep track of processes running on the system and manage them. Cfruby is also useful in this regard, providing a way to effectively process processes.

You can use Cfruby to implement it.
Listing 10. Using Cfgrubyscript for process management

Require ' RubyGems '

require_gem ' cfruby ' require '

libcfruby/cfrubyscript '

$proc. Kill ($proc. Vim)

' Ps–aef '. EXEC ()

What does the above code do?

    • Line 3rd – Use the Global Processmanager object $proc to turn off the "vim" process specified by the parameter. $proc. Vim is an object of the ProcessInfo type of the "vim" process running on the system. They are created automatically by Cfrubyscript.
    • Line 4th – Start a new process with the specified command "PS–AEF". You can call the Exec method directly from the command string.

Package Management

Another task that a system administrator must be responsible for is managing the packages on the system. Cfruby provides a number of ways to easily install and remove software on your system.
Listing 11. Using Cfgrubyscript for package management

Require ' RubyGems '

require_gem ' cfruby ' require ' libcfruby/cfrubyscript ' all

= $pkg. Packages ()

Installed = $pkg. Installed_packages ()

Ruby.install ()

What does the above code do?

    • Line 3rd – Use the global $pkg Packagemanager object created by Cfrubyscript to obtain all the available packages on the system by calling the packages () method.
    • Line 4th – Get a list of all installed packages.
    • Line 5th – Install the Ruby package by calling the install method. The install helper method can be invoked directly through the package name itself.

It's just so simple.
File Management

Cfruby can also help manage files on your system. By using the methods provided by Cfruby, you can easily create, edit, delete, change ownership and change permissions, and so on.
Listing 12. Using Cfgrubyscript for file management

Require ' rubygems ' require_gem ' cfruby ' require ' libcfruby/cfrubyscript '/etc/ssh '

. Chown_mod (' Root ', ' wheel ', ' u=rw,g=r,o-rwx ', ': Recursive ' => true)

What does the above code do?

Line 3rd – Change the owner and group of the file "/etc/ssh" and the license. Call the Chown_mod () method directly from the file itself. In this way, this is done through the helper object and method of the Cfrubyscript. Note that this feature is implemented in a single line.

So, the above example should have given you an idea of how powerful Cfruby is and how easy it is to manage the system with it. And, because it provides a very intuitive set of classes and methods, it makes the entire task of system administration easier and more interesting.

There's a lot more to know about Cfruby and its set of features. It comes with a good set of documents. It is recommended that you take a look at these documents in order to release the full power of this Ruby library. Check the Resources section for links.

Conclusion

Not only can Ruby work with the Rails framework for WEB application development. It can also be as powerful as a scripting language, a good substitute for common shell scripting, and often used to implement scripting requirements in System management.

By using Ruby's set of built-in modules and some external libraries, system administrators can become more efficient and more fun to work with. Ruby is a very useful and powerful tool and is a necessary tool in each system administrator's toolbox.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.