本文整理汇总了Python中nmap.PortScanner类的典型用法代码示例。如果您正苦于以下问题:Python PortScanner类的具体用法?Python PortScanner怎么用?Python PortScanner使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了PortScanner类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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)
示例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
示例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
示例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()
示例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
示例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
示例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)
示例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
示例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
示例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)
示例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)
示例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)
示例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()
示例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
示例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'])