本文整理汇总了Python中nmap.PortScanner类的典型用法代码示例。如果您正苦于以下问题:Python PortScanner类的具体用法?Python PortScanner怎么用?Python PortScanner使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PortScanner类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: run
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)
开发者ID:DaniLabs,项目名称:rexploit,代码行数:31,代码来源:scanthread.py
示例2: run
def run(self):
"""Scan the network for MAC addresses and keep tabs on which devices
are present or have left"""
nm = PortScanner()
while self.running:
# Decrement all hosts
for mac in self.macs:
if self.macs[mac] > 0:
self.macs[mac] -= 1;
nm.scan(hosts = self.local_net, arguments = self.nmap_args)
# Mark each host found as present unless it is not tracked
for host in nm.all_hosts():
try:
mac = nm[host]['addresses']['mac']
if mac in self.macs:
self.macs[mac] = self.timeout + 1 # Immediately decremented
except KeyError:
# nmap didn't get the MAC?
# Just ignore it I guess
pass
开发者ID:reynoldsbd3,项目名称:whoshome,代码行数:25,代码来源:networkscanner.py
示例3: check_passive_port_task
def check_passive_port_task(request, module_key):
module = Module.objects.get(id=module_key)
debug(module, ("begin",))
events = ModuleEvent.objects.filter(module=module).filter(back_at=None)
portscanner = PortScanner()
result = None
try:
if not module.check_port:
raise Exception("Improperly configured")
portscanner.scan(arguments = NMAP_ARGS, ports=str(module.check_port), hosts=module.host.encode('ascii','ignore'))
now = datetime.datetime.now()
host = portscanner.all_hosts()[0]
if 'open' == portscanner[host]['tcp'][module.check_port]['state']:
debug(module, "Port open")
for event in events:
event.back_at = now
event.save()
debug(module,"Site is back online %s" % module.name)
else:
if not events:
_create_new_event(module, "off-line", now, None, "Port is closed")
except KeyError, e:
pass
开发者ID:BackOfficeCoPT,项目名称:site-status,代码行数:28,代码来源:views.py
示例4: main
def main(argv):
iprange = None
try:
opts, args = getopt.gnu_getopt(argv,"i:",["iprange="])
except getopt.GetoptError:
print sys.argv[0]+' -i <iprange>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print sys.argv[0]+' -i <iprange>'
sys.exit()
elif opt in ("-i", "--iprange"):
iprange = arg
if iprange is None:
print sys.argv[0]+' -i <iprange>'
sys.exit()
scan_port = int(cfg.getConfigValue('pdu', 'scan_port'))
snmp_port = int(cfg.getConfigValue('pdu', 'snmp_port'))
ro_community = cfg.getConfigValue('pdu', 'ro_community')
rw_community = cfg.getConfigValue('pdu', 'rw_community')
dccode = cfg.getConfigValue('pdu', 'dccode')
url = '%s/pdu/update' % cfg.getConfigValue('pdu', 'api_base')
nm = PortScanner()
nm.scan(hosts=iprange, arguments='-n -p %s' % (scan_port))
for host in nm.all_hosts():
state = nm[host]['tcp'][scan_port]['state']
t = Thread(target=probePdu, args=(host, state, snmp_port, ro_community, rw_community, dccode, url))
t.start()
开发者ID:DiData,项目名称:pdumgr,代码行数:34,代码来源:pdumgr.py
示例5: NmapParser
class NmapParser(TestPlugin):
def __init__(self):
self.tool_name = "nmap"
super(NmapParser, self).__init__("nmap")
self.nm = PortScanner()
self.hosts = None
self.ports = None
self.argments = "-sV"
self.resultparser = ResultPlugin()
def args_status(self):
print "hosts:", self.hosts, "\n"
print "ports:", self.ports, "\n"
print "argments:", self.argments, "\n"
def start_scan(self):
if self.hosts is not None:
self.nm.scan(self.hosts, arguments=self.argments)
if self.ports is not None:
self.nm.scan(self.hosts, self.ports, arguments=self.argments)
else:
print "please set hosts"
def scan_result(self):
if self.hosts is not None and self.nm.all_hosts():
return self.nm[self.hosts]
def run(self):
super(NmapParser, self).run()
print "scanning .................\n", "please wait!\n"
self.start_scan()
def status(self):
self.args_status()
def result(self):
if self.scan_result() is not None:
self.resultparser.set_hostname(self.scan_result().hostname())
self.resultparser.set_state(self.scan_result().state())
self.resultparser.set_address(self.hosts)
self.resultparser.set_openports(self.scan_result().all_tcp())
if u"tcp" in self.scan_result():
self.resultparser.set_servers(self.scan_result()[u"tcp"])
print "hostname:", self.resultparser.get_hostname
print "address:", self.resultparser.get_address
print "state is :", self.resultparser.get_state
print "open ports:", self.resultparser.get_openports
print "servers:", self.resultparser.get_servers, "\n"
def set_arg(self, arg1, arg2):
if arg1 == "hosts":
self.hosts = arg2
elif arg1 == "ports":
self.ports = arg2
elif arg1 == "argments":
self.argments = arg2
开发者ID:nolol,项目名称:coffesploit,代码行数:57,代码来源:nmapparser.py
示例6: run_test
def run_test(self):
"""Check the port is open on the remote host"""
ps = PortScanner()
scan = ps.scan(hosts=self.host, ports=self.port, arguments='--host-timeout ' + str(self.timeout) + 's')
try:
if scan['scan'][str(self.host)]['tcp'][int(self.port)]['state'] == 'open':
return True
else:
return False
except KeyError: # If we cannot find the info in the key for the status, this means the host is down
return False
开发者ID:Darkpaw95,项目名称:NetworkMonitor,代码行数:11,代码来源:network.py
示例7: nm_scan
def nm_scan(hosts, ports, args='-T4 -A'):
print("From" , platform.uname()[0], platform.uname()[2])
print("On", datetime.datetime.now().ctime())
print("Scanning for host", hosts)
try:
nm = PortScanner()
result = nm.scan(hosts=hosts, ports=ports, arguments=args, sudo=False)
return result
except:
print("[-] Error!!! Something is wrong,")
print("| (network trouble / nmap problem) ")
print("| make sure you have nmap installed ")
print("|__ Please try ./pvascan.py -h\n")
exit(0)
开发者ID:aldoridhoni,项目名称:pvascan,代码行数:14,代码来源:pvascan.py
示例8: _update_info
def _update_info(self):
"""Scan the network for devices.
Returns boolean if scanning successful.
"""
_LOGGER.info("Scanning")
from nmap import PortScanner, PortScannerError
scanner = PortScanner()
options = "-F --host-timeout 5s "
exclude = "--exclude "
if self.home_interval:
boundary = dt_util.now() - self.home_interval
last_results = [device for device in self.last_results if device.last_update > boundary]
if last_results:
# Pylint is confused here.
# pylint: disable=no-member
exclude_hosts = self.exclude + [device.ip for device in last_results]
else:
exclude_hosts = self.exclude
else:
last_results = []
exclude_hosts = self.exclude
if exclude_hosts:
exclude = " --exclude {}".format(",".join(exclude_hosts))
options += exclude
try:
result = scanner.scan(hosts=self.hosts, arguments=options)
except PortScannerError:
return False
now = dt_util.now()
for ipv4, info in result["scan"].items():
if info["status"]["state"] != "up":
continue
name = info["hostnames"][0]["name"] if info["hostnames"] else ipv4
# Mac address only returned if nmap ran as root
mac = info["addresses"].get("mac") or _arp(ipv4)
if mac is None:
continue
last_results.append(Device(mac.upper(), name, ipv4, now))
self.last_results = last_results
_LOGGER.info("nmap scan successful")
return True
开发者ID:heathbar,项目名称:home-assistant,代码行数:50,代码来源:nmap_tracker.py
示例9: _update_info
def _update_info(self):
"""Scan the network for devices.
Returns boolean if scanning successful.
"""
_LOGGER.info('Scanning')
from nmap import PortScanner, PortScannerError
scanner = PortScanner()
options = '-F --host-timeout 5s '
if self.home_interval:
boundary = dt_util.now() - self.home_interval
last_results = [device for device in self.last_results
if device.last_update > boundary]
if last_results:
exclude_hosts = self.exclude + [device.ip for device
in last_results]
else:
exclude_hosts = self.exclude
else:
last_results = []
exclude_hosts = self.exclude
if exclude_hosts:
options += ' --exclude {}'.format(','.join(exclude_hosts))
try:
result = scanner.scan(hosts=' '.join(self.hosts),
arguments=options)
except PortScannerError:
return False
now = dt_util.now()
for ipv4, info in result['scan'].items():
if info['status']['state'] != 'up':
continue
name = info['hostnames'][0]['name'] if info['hostnames'] else ipv4
# Mac address only returned if nmap ran as root
mac = info['addresses'].get('mac') or _arp(ipv4)
if mac is None:
continue
last_results.append(Device(mac.upper(), name, ipv4, now))
self.last_results = last_results
_LOGGER.info('nmap scan successful')
return True
开发者ID:krzynio,项目名称:home-assistant,代码行数:48,代码来源:nmap_tracker.py
示例10: scan_host
def scan_host(host):
"""
Utilizza nmap per ricercare i servizi sull'host... la scansione e'
di tipo probing, nel senso che effettua delle prove sulle varie
porte per determinare il tipo di servizio, ritorna un oggetto
contenente i risultati sulla scansione (che tra l'altro e' l'oggetto
stesso che contiene il metodo per la scansione)
"""
scanner = PortScanner()
print("Checking services on %s" % host)
scanner.scan(hosts=host,
arguments='--host_timeout 60s -sV --version_light')
return(scanner)
开发者ID:michelesr,项目名称:network-monitor-server,代码行数:16,代码来源:scan.py
示例11: get_ports_from_report
def get_ports_from_report(nmap_report):
"""
This function is responsible to take XML file and generate the report details.
"""
scanner = PortScanner()
try:
scan_result = scanner.analyse_nmap_xml_scan(open(nmap_report).read())
for host in scan_result['scan']:
try:
for port, port_details in scan_result['scan'][host]['tcp'].items():
yield host, port, port_details
except exceptions.KeyError:
pass
except Exception, error:
LOGGER.error("Error: %s" % error)
exit(1)
开发者ID:jwhitney83,项目名称:AutoBrowser,代码行数:16,代码来源:AutoBrowser.py
示例12: scan
def scan(self, bot, update, args):
chat_id = update.message.chat_id
from_user = update.message.from_user.username
parser = ArgumentParser(prog='nmap_plugin')
parser.add_argument('-host', required=True)
parser.add_argument('-ports', required=False, default=None)
parser.add_argument('-all', required=False, default=False, type=bool)
parser.add_argument('-raw', required=False, default=None)
try:
p = parser.parse_args(args)
for param in vars(p):
if self.__check_for_idiot_friends(getattr(p, param)):
bot.sendMessage(
chat_id,
text='{} you are a funny guy... but go to try to be an h4x0r somewhere else.'.format(from_user)
)
if from_user == 'dzonerzy':
bot.sendMessage(chat_id,
text='Amico del jaguaro... Ti fo un rutto ne `i viso che ti fo diventa` bello!'
)
return
except ArgumentError:
bot.sendMessage(chat_id, text="Wrong parameters passed.")
return
arguments = '-sV'
if p.all is True:
arguments = '-A'
bot.sendMessage(chat_id, text="Command accepted, running nmap against: {}".format(p.host))
nm = PortScanner()
nm.scan(hosts=p.host, ports=p.ports, arguments=arguments)
msg = ''
for host in nm.all_hosts():
msg = '----------------------------------------------------\n'
msg += 'Host: {} ({})\n'.format(host, nm[host].hostname())
msg += 'State: {}\n'.format(nm[host].state())
for proto in nm[host].all_protocols():
msg += 'Protocol : {}\n'.format(proto)
lport = nm[host][proto].keys()
lport.sort()
for port in lport:
msg += '\tport : {}\tstate : {}\n'.format(port, nm[host][proto][port]['state'])
msg = 'Empty response object received.' if msg == '' else msg
bot.sendMessage(chat_id, text=msg)
开发者ID:blackms,项目名称:myTelegramBot,代码行数:47,代码来源:nmap_plugin.py
示例13: __init__
def __init__(self):
self.tool_name = "nmap"
super(NmapParser, self).__init__("nmap")
self.nm = PortScanner()
self.hosts = None
self.ports = None
self.arguments = "-sV"
self.resultparser = ResultPlugin()
开发者ID:Mithrilwoodrat,项目名称:coffesploit,代码行数:8,代码来源:nmapparser.py
示例14: run
def run(self):
nm = PortScanner()
a=nm.scan(hosts=self.gateway, arguments='-sU --script nbstat.nse -O -p137')
for k,v in a['scan'].iteritems():
if str(v['status']['state']) == 'up':
try:
ip = str(v['addresses']['ipv4'])
hostname = str(v['hostscript'][0]['output']).split(',')[0]
hostname = hostname.split(':')[1]
mac = str(v['hostscript'][0]['output']).split(',')[2]
if search('<unknown>',mac):mac = '<unknown>'
else:mac = mac[13:32]
self.result = ip +'|'+mac.replace('\n','')+'|'+hostname.replace('\n','')
self.emit(SIGNAL('Activated( QString )'),
self.result)
except :
pass
开发者ID:XCHADXFAQ77X,项目名称:3vilTwinAttacker,代码行数:17,代码来源:utils.py
示例15: nmapScan
def nmapScan(target):
nm = PortScanner()
sc = nm.scan(hosts=target, arguments="-n -T4 -sV -p 21,22,23,25,53,80,110,143,443,465,995,993,1248,1433,3306,3389")
global siteIP
siteIP = sc["scan"].keys()[0]
key, value, total = sc["scan"][siteIP]["tcp"].keys(), sc["scan"][siteIP]["tcp"].values(), len(sc["scan"][siteIP]["tcp"].keys())
print bold+"Port\t\tName\t\tVersion\t\tStatus"+endcolor
print "----\t\t------\t\t----\t\t-------"
for port in range(total):
if value[port]["state"] == "open":
portlist.append(key[port])
else:
pass
print "{}\t\t{}\t\t{}\t\t{}".format(key[port], value[port]["name"], value[port]["version"], value[port]["state"])
print ""
print "Scan Time : {}".format(sc["nmap"]['scanstats']['timestr'])
print "Scan Interval : {}".format(sc["nmap"]['scanstats']['elapsed'])
开发者ID:ExitStars,项目名称:KingCobra,代码行数:17,代码来源:king.py
示例16: run
def run(self):
nm = PortScanner()
a=nm.scan(hosts=config_getway, arguments='-sU --script nbstat.nse -O -p137')
for k,v in a['scan'].iteritems():
if str(v['status']['state']) == 'up':
try:
ip = str(v['addresses']['ipv4'])
hostname = str(v['hostscript'][0]["output"]).split(",")[0]
hostname = hostname.split(":")[1]
mac = str(v['hostscript'][0]["output"]).split(",")[2]
if search("<unknown>",mac):
mac = "<unknown>"
else:
mac = mac[13:32]
self.result = ip +"|"+mac.replace("\n","")+"|"+hostname.replace("\n","")
self.emit(SIGNAL("Activated( QString )"),self.result)
except :
pass
开发者ID:Mohammedmustaf,项目名称:3vilTwinAttacker,代码行数:18,代码来源:arps_Posion.py
示例17: NmapParser
class NmapParser(ScanPlugin):
def __init__(self):
self.tool_name = "nmap"
super(NmapParser, self).__init__("nmap")
self.nm = PortScanner()
self.hosts = None
self.ports = None
self.arguments = "-sV"
self.resultparser = ResultPlugin()
def start_scan(self):
if self.hosts is not None:
self.nm.scan(self.hosts, arguments=self.arguments)
if self.ports is not None:
self.nm.scan(self.hosts, self.ports, arguments=self.arguments)
else:
print 'please set hosts'
def scan_result(self):
if self.hosts is not None and self.nm.all_hosts():
return self.nm[self.hosts]
def run(self, status):
if status and len(status) == 3:
self.hosts = status['hosts']
self.ports = status['ports']
self.arguments = status['arguments']
super(NmapParser, self).run(status)
print "scanning .................\n", "please wait!\n"
self.start_scan()
def status(self):
return {"hosts": self.hosts, "ports": self.ports, "arguments": self.arguments}
def result(self):
if self.scan_result() is not None:
self.resultparser.set_hostname(self.scan_result().hostname())
self.resultparser.set_state(self.scan_result().state())
self.resultparser.set_address(self.hosts)
self.resultparser.set_openports(self.scan_result().all_tcp())
if u'tcp' in self.scan_result():
self.resultparser.set_servers(self.scan_result()[u'tcp'])
self.resultparser.log_result()
return self.scan_result()
开发者ID:Mithrilwoodrat,项目名称:coffesploit,代码行数:44,代码来源:nmapparser.py
示例18: _update_info
def _update_info(self):
"""
Scans the network for devices.
Returns boolean if scanning successful.
"""
_LOGGER.info("Scanning")
from nmap import PortScanner, PortScannerError
scanner = PortScanner()
options = "-F --host-timeout 5"
exclude_targets = set()
if self.home_interval:
now = dt_util.now()
for host in self.last_results:
if host.last_update + self.home_interval > now:
exclude_targets.add(host)
if len(exclude_targets) > 0:
target_list = [t.ip for t in exclude_targets]
options += " --exclude {}".format(",".join(target_list))
try:
result = scanner.scan(hosts=self.hosts, arguments=options)
except PortScannerError:
return False
now = dt_util.now()
self.last_results = []
for ipv4, info in result['scan'].items():
if info['status']['state'] != 'up':
continue
name = info['hostnames'][0] if info['hostnames'] else ipv4
# Mac address only returned if nmap ran as root
mac = info['addresses'].get('mac') or _arp(ipv4)
if mac is None:
continue
device = Device(mac.upper(), name, ipv4, now)
self.last_results.append(device)
self.last_results.extend(exclude_targets)
_LOGGER.info("nmap scan successful")
return True
开发者ID:rohitranjan1991,项目名称:home-assistant,代码行数:42,代码来源:nmap_tracker.py
示例19: host_discovery
def host_discovery(network_address):
"""
Tramite il modulo nmap viene effettuata una ricerca degli host
attivi in rete. Ritorna una lista degli host attivi in rete.
"""
scanner = PortScanner()
if network_address:
print("Searching for hosts on %s..." % network_address)
scanner.scan(hosts=network_address, arguments='-sP')
iplist = [ip for ip in scanner.all_hosts()
if scanner[ip].state() == 'up']
print("Found %s host(s)" % len(iplist))
print(iplist)
return iplist
开发者ID:michelesr,项目名称:network-monitor-server,代码行数:21,代码来源:scan.py
示例20: run
def run(self):
try:
nm = PortScanner()
a = nm.scan(hosts=self.gateway, arguments="-sU --script nbstat.nse -O -p137")
for k, v in a["scan"].iteritems():
if str(v["status"]["state"]) == "up":
try:
ip = str(v["addresses"]["ipv4"])
hostname = str(v["hostscript"][0]["output"]).split(",")[0]
hostname = hostname.split(":")[1]
mac = str(v["hostscript"][0]["output"]).split(",")[2]
if search("<unknown>", mac):
mac = "<unknown>"
else:
mac = mac[13:32]
self.result = ip + "|" + mac.replace("\n", "") + "|" + hostname.replace("\n", "")
self.emit(SIGNAL("Activated( QString )"), self.result)
except:
pass
except NameError:
QMessageBox.information(self, "error module", "the module Python-nmap not installed")
开发者ID:paran0ids0ul,项目名称:3vilTwinAttacker,代码行数:21,代码来源:utils.py
注:本文中的nmap.PortScanner类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论