Mastering Metasploit
上QQ阅读APP看书,第一时间看更新

Defining methods in the shell

A method or a function is a set of statements that will execute when we make a call to it. We can declare methods easily in Ruby's interactive shell, or we can declare them using scripts. Knowledge of methods is important when working with Metasploit modules. Let's see the syntax:

def method_name [( [arg [= default]]...[, * arg [, &expr ]])]
expr
end  

To define a method, we use def followed by the method name, with arguments and expressions in parentheses. We also use an end statement, following all of the expressions to set an end to the method's definition. Here, arg refers to the arguments that a method receives. Also, expr refers to the expressions that a method receives or calculates inline. Let's have a look at an example:

irb(main):002:0> def xorops(a,b)
irb(main):003:1> res = a ^ b
irb(main):004:1> return res
irb(main):005:1> end
=> :xorops  

We defined a method named xorops, which receives two arguments named a and b. Furthermore, we XORed the received arguments and stored the results in a new variable called res. Finally, we returned the result using the return statement:

irb(main):006:0> xorops(90,147)
=> 201  

We can see our function printing out the correct value by performing the XOR operation. Ruby offers two different functions to print the output: puts and print. When it comes to the Metasploit framework, the print_line function is primarily used. However, symbolizing success, status, and errors can be done using print_good, print_status, and print_error statements, respectively. Let's look at some examples here:

print_good("Example of Print Good") 
print_status("Example of Print Status") 
print_error("Example of Print Error") 

These print methods, when used with Metasploit modules, will produce the following output that depicts the green + symbol for good, the blue * for denoting status messages, and the red - symbol representing errors:

[+] Example of Print Good
[*] Example of Print Status
[-] Example of Print Error  

We will see the workings of various print statement types in the latter half of this chapter.