Tutorial on system management by writing scripts in Ruby, and ruby System Management

Source: Internet
Author: User

Tutorial on system management by writing scripts in Ruby, and ruby System Management

Introduction

Ruby is an extremely rich, free, simple, scalable, portable, and object-oriented scripting language. Recently, it is widely used in the Web field. To a certain extent, this is attributed to the very powerful Web application development framework Rails, Which is exactly written in Ruby. Rails, also known as Ruby on Rails (ROR), provides a very powerful platform for rapid and effective Web application development. It is highly scalable. Many websites on the Web are built using Ruby on Rails.

In addition to using Rails as a Web application development platform, Ruby is rarely mentioned, that is, as a powerful scripting language, like Python or Perl. It has very powerful functions, because it can use a lot of built-in and external libraries, so it can use its power to solve many script programming requirements in the general system management work environment.

System Management requires a large number of scripts to make things simpler and more effective. Writing scripts can better meet user management, process management, file management, software package management, and other basic automation requirements than monotonous manual work. Ruby is very useful in this scenario. It has a set of good libraries to meet this requirement.

For this article, I assume that the reader has Ruby application knowledge. The basic examples provided here use pure Ruby, so any UNIX-like classes supported by Ruby can be used? System and Windows? . For more advanced Cfruby examples, a UNIX system is required. All the examples below are already in a Linux? Ruby v1.8.4 is used on the machine for testing. They should also be used in the latest Ruby version.

Ruby in practice

In the first example, search for files that match the specified mode in the specified path and provide detailed information about these files in a user-friendly manner. To achieve this goal, you don't have to rely on any command line utility, but you only need to use Ruby's built-in APIs. Therefore, this example can be run on any platform running Ruby.

In addition, this example shows how powerful Ruby is to simplify script writing. Rather than simply simulating the * nix "find" command, it is built on the command, so it has a strong customization capability when using Ruby.
Listing 1. Search for files that match the specified mode in a given path and display their details

require 'find'puts ""puts "-----------------------File Search-----------------------------------"puts ""print "Enter the search path  : "searchpath = getssearchpath = searchpath.chompputs ""print "Enter the search pattern : "pattern = getspattern = pattern.chompputs"----------------------------------------------------------------------"puts "Searching in " + searchpath + " for files matching pattern " + patternputs"----------------------------------------------------------------------"puts "" Find.find(searchpath) do |path|  if FileTest.directory?(path)   if File.basename(path)[0] == ?.    Find.prune    # Don't look any further into 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:

  • Lines 5th-11-request the user to provide the search path and search mode.
  • Row 3-use the "Find" method in the "find" class in Ruby to traverse the specified search path.
  • Row 3-check whether the detected file is a directory. If the directory is not ".", recursively traverse the directory.
  • Row 3-use the "fnmatch" method in the "File" class to check whether the detected File conforms to the specified mode.
  • Lines 25th-34-if the file meets the pattern, the detailed information of the file is printed.

The following is an example output of this script.
Listing 2. example output of the first example

[root@logan]# ruby findexample.rb-----------------------File Search-----------------------------------Enter the search path  : /testEnter the search pattern : *.rb----------------------------------------------------------------------Searching in /test for files matching pattern *.rb----------------------------------------------------------------------Filename   : s.rbPermissions : 100644Owning uid  : 1Owning gid  : 1Size (bytes) : 57---------------------------------------------------Filename   : test.rbPermissions : 100644Owning uid  : 0Owning gid  : 0Size (bytes) : 996---------------------------------------------------Filename   : s1.rbPermissions : 100644Owning uid  : 1Owning gid  : 1Size (bytes) : 39---------------------------------------------------

During system management, the most common requirement is to effectively use zip files to manage backups, or transfer a group of files from one computer to another. Ruby has many advantages in this regard. The second example is built on the basis of the first example, but contains a scenario where you need to package the searched files into a zip file.

The built-in zlib module can be used to process gzip files, which is good enough in most cases. However, here I will use another good Ruby library, "rubyzip", to create and process zip archives. Please refer to the reference section and find the download link. Note that this example uses pure Ruby, which does not depend on any command line utility currently provided on the computer.

Install rubyzip

Download the "rubyzip" gem through the provided link and copy it to the system. (At the time of writing this article, its file name is "rubyzip-0.9.1.gem ").
Run the gem installation rubyzip-0.9.1.gem

Listing 3. Using a zip file

require 'rubygems'require_gem 'rubyzip'require 'find'require 'zip/zip'puts ""puts "------------------File Search and Zip-----------------------------"puts ""print "Enter the search path  : "searchpath = getssearchpath = searchpath.chompputs ""print "Enter the search pattern : "pattern = getspattern = pattern.chompputs"----------------------------------------------------------------------"puts "Searching in " + searchpath + " for files matching pattern " + patternputs"----------------------------------------------------------------------"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 into this directory.   else    next   end  else    if File.fnmatch(pattern,File.basename(path))        p File.basename(path)        zipfile.add(File.basename(path),path)    end  end end }

This script creates a zip file named unzip test.zip Based on the provided search path and search mode.

In this example, do the following:

  • Lines 9th-15-the user is requested to provide the search path and search mode.
  • Row 3-create a new ZipFile named unzip test.zip.
  • Row 3-use the "Find" method in the "find" class in Ruby to traverse the specified search path.
  • Row 3-check whether the detected file is a directory. If the directory is not ".", recursively traverse the directory.
  • Row 3-use the "fnmatch" method in the "File" class to check whether the detected File conforms to the specified mode.
  • Row 3-Add the matching files to the zip archive.

The following is an example output:
Listing 4. sample output in the second example

[root@logan]# ruby zipexample.rb-----------------------File Search-----------------------------------Enter the search path  : /testEnter the search pattern : *.rb----------------------------------------------------------------------Searching in /test for files matching pattern *.rb--------------------------------------------------------------------------------------------------------------------------------------------Zipping up the found files...----------------------------------------------------------------------"s.rb""test.rb""s1.rb"[root@logan]# unzip -l test.zipArchive: test.zip Length   Date  Time  Name --------  ----  ----  ----   996 09-25-08 21:01  test.rb   57 09-25-08 21:01  s.rb   39 09-25-08 21:01  s1.rb --------          -------  1092          3 files

Cfruby-Advanced System Management

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

Cfruby is basically a package consisting of two parts:

  1. Cfrubylib-a pure Ruby library that contains classes and methods used for system management. This includes file copy, search, checksum and check, package management, and user management.
  2. Cfenjin-a simple scripting language that helps you write scripts for system management tasks (without having to know Ruby ).

Cfruby can be downloaded as a Ruby gem or tar compressed file. Gem is the simplest and easiest way. Obtain the gem and run the "gem install" command to install it.

Install Cfruby:

  • Copy the downloaded Cfruby gem file to the system. (At the time of writing this article, its file name is "cfruby-1.01.gem ").
  • Run the gem install cfruby-1.01.gem.

Cfruby should be installed on the system now.
Use Cfruby

Now I will show you the functions of Cfruby and how it greatly simplifies system management.

There are two basic methods to access the functions provided by the Cfruby Library:

  1. Use the Ruby class in libcfgruby directly.
  2. The cfrubyscript package provides libcfruby with a simpler interface.

Directly use the Ruby class in libcfruby

Libcfruby is the core of Cfruby. It contains a group of modules that provide various functions to simplify system maintenance and settings. To use libcfruby, you need to add "require_gem 'cfruby'" to the top of the script after installing Cfruby gem. In this way, you can directly access all the core modules in libcfruby and use them in any way as needed in the script. The only drawback of this method is that libcfruby is relatively large, which puts all classes and methods into their respective namespaces. Therefore, to access any class, it must be limited by namespaces. For example, libcfruby provides a method for obtaining the system type. To obtain the type of the operating system, do the following:
Listing 5. Use libcfruby to obtain the operating system type

require 'rubygems'require_gem 'cfruby'os = Cfruby::OS::OSFactory.new.get_os()puts(os.name)

This is only the name of the operating system. As you use libcfruby to do more things, your script will be filled with more statements with a specified namespace. Because of this, it is very convenient to use the Cfruby method.
The cfrubyscript package provides libcfruby with a simpler interface.

To use the cfrubyscript package, you need to add:
Listing 6. Using cfrubyscript

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

In this way, cfrubyscript is included in the script, and then the libcfruby function can be accessed through a simpler interface.

Cfrubyscript does the following:

  • It exports a set of variables to the global namespace, such as $ OS, $ pkg, $ user, $ proc, and $ sched.
  • It stores most major modules in the primary namespace, so you can call FileEdit. set instead of Cfruby: FileEdit. set.
  • It adds many helper methods for String and Array. These methods can do some Cfruby tasks (install programs, edit files, and so on ).
  • It also provides a good logger.

Therefore, you do not need to specify a large number of namespaces in the script. The example used to obtain the operating system type above is now as follows:
Listing 7. Use cfrubyscript to obtain the operating system type

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 indeed powerful and provides many functions for * nix management systems.

Now let's take a look at some of the functions and some basic examples of using them.
User Management

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

This task is implemented using the UserManager object, which can be obtained from the OS module as follows.
Listing 8. Use libcfruby to obtain the UserManager object

require 'rubygems'require_gem 'cfruby'osfactory = Cfruby::OS::OSFactory.new()os = osfactory.get_os()usermgr = os.get_user_manager()

If cfrubyscript is used, a global user management object, namely $ user, can be directly used to call methods. 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 is the above Code doing?

  • Lines 1st and 2-libcfruby and cfrubyscript are included in the script as usual.
  • Row 3-create a new user with the password specified by the username "newusername" and the second parameter.
  • Row 3-delete a user with the username "usernametodelete. The second parameter can be set to true or false to specify whether to delete the user's home directory.

Similarly, you can use the addgroup () and deletegroup () methods in the UserManager object to complete group operations.
Process Management

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

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 is the above Code doing?

  • Row 3rd-use the global ProcessManager object $ proc to close the "vim" process specified by the parameter. $ Proc. vim is a ProcessInfo-type object of the "vim" process running on the system. They are automatically created by cfrubyscript.
  • Line 3-start a new process with the specified command "ps-aef. You can directly call the exec method from the command string.

Package Management

Another task that the system administrator must be responsible for is to manage packages on the system. Cfruby provides methods to conveniently install and delete software on the 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 is the above Code doing?

  • Row 3rd-use the global $ pkg PackageManager object created using cfrubyscript to obtain all available packages on the system by calling the packages () method.
  • Row 3-get a list of all installed packages.
  • Line 2-install the Ruby package by calling the install method. You can directly call the install assistant method by using the package name itself.

It's that simple.
File Management

Cfruby can also help you manage files on the system. By using the methods provided by Cfruby, you can easily create, edit, delete, change ownership, and change licenses.
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 is the above Code doing?

Row 3-change the owner, group, and license of the file "/etc/ssh. Call the chown_mod () method directly from the file itself. In this way, this is implemented through the Helper Objects and methods of cfrubyscript. Note that only one row is used to implement this function.

Therefore, the above example should show you how powerful Cfruby is and how easy it is to use it to manage the system. Moreover, it provides a set of intuitive classes and methods, making the entire task managed by the system easier and more interesting.

There is still much to know about Cfruby and its complete set of functions. It comes with a set of good documentation. We recommend that you take a look at these documents to release all the power of this Ruby library. For more information, see the references section.

Conclusion

Ruby can be used together with the Rails framework for Web application development. It can also be as powerful as the scripting language, as a good alternative to common shell scripting, and is often used to meet the script programming requirements in system management.

By using Ruby's built-in modules and some external libraries, system administrators can become more efficient and work more interesting. Ruby is a very useful and powerful tool that is essential to every system administrator 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.