本文整理汇总了Python中libnmap.process.NmapProcess类的典型用法代码示例。如果您正苦于以下问题:Python NmapProcess类的具体用法?Python NmapProcess怎么用?Python NmapProcess使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了NmapProcess类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: nmap_script_scan
def nmap_script_scan(self, target, portlist=None, version_intense="0", script_name=None):
'''
Runs nmap with the -sC arg or the --script arg if script_name is provided. Options used are: -sV --version-intensity <default:0> -sC|--script=<script_name>
Arguments:
- ``target``: IP or the range of IPs that need to be tested
- ``portlist``: list of ports, range of ports that need to be tested. They can either be comma separated or separated by hyphen
example: 121,161,240 or 1-100
- ``version_intense``: Version intensity of OS detection
- ``script_name``: Script Name that needs to be referenced
Examples:
| nmap script scan | target | portlist | version_intense | script_name |
'''
target = str(target)
if portlist and script_name:
nmap_proc_cmd = "-Pn -sV --version-intensity {0} --script={1} -p {2}".format(version_intense, script_name, portlist)
elif portlist and not script_name:
nmap_proc_cmd = "-Pn -sV --version-intensity {0} -sC -p {1}".format(version_intense, portlist)
elif script_name and not portlist:
raise Exception('EXCEPTION: If you use specific script, you have to specify a port')
else:
nmap_proc_cmd = "-Pn -sV --version-intensity {0} -sC".format(version_intense)
nmproc = NmapProcess(target, nmap_proc_cmd)
rc = nmproc.run()
if rc != 0:
raise Exception('EXCEPTION: nmap scan failed: {0}'.format(nmproc.stderr))
try:
parsed = NmapParser.parse(nmproc.stdout)
print parsed
self.results = parsed
except NmapParserException as ne:
print 'EXCEPTION: Exception in parsing results: {0}'.format(ne.msg)
示例2: start
def start(self):
''' Start Discovery '''
logs = core.logs.Logger(config=self.config, proc_name="discovery.nmap")
logger = logs.getLogger()
logger = logs.clean_handlers(logger)
logger.info("Starting scan of environment")
try:
nmap = NmapProcess(self.config['discovery']['plugins']['nmap']['target'],
options=self.config['discovery']['plugins']['nmap']['flags'])
except Exception as e:
raise Exception("Failed to execute nmap process: {0}".format(e.message))
up = []
while True:
nmap.run()
nmap_report = NmapParser.parse(nmap.stdout)
for scanned_host in nmap_report.hosts:
if "up" in scanned_host.status and scanned_host.address not in up:
up.append(scanned_host.address)
logger.debug("Found new host: {0}".format(scanned_host.address))
if self.dbc.new_discovery(ip=scanned_host.address):
logger.debug("Added host {0} to discovery queue".format(
scanned_host.address))
else:
logger.debug("Failed to add host {0} to discovery queue".format(
scanned_host.address))
logger.debug("Scanned {0} hosts, {1} found up".format(
len(nmap_report.hosts), len(up)))
time.sleep(self.config['discovery']['plugins']['nmap']['interval'])
return True
示例3: celery_nmap_scan
def celery_nmap_scan(targets, options):
"""celery_nmap_scan task"""
def status_callback(nmapscan=None):
"""status callback"""
try:
celery_nmap_scan.update_state(state="PROGRESS",
meta={"progress": nmapscan.progress,
"ready": 0,
"etc": nmapscan.etc})
except Exception as e:
print("status_callback error: " + str(e))
# scan is not yet finished (or even started).
# But I need to do this before the NmapProcess is started because
# otherwise other tasks might be queued in front of this!
_nmap_task_id = celery_nmap_scan.request.id
store_nmap_report_meta.apply_async(kwargs={'nmap_task_id': str(_nmap_task_id)})
print("tasks.py: Targets and Options")
print(targets)
print(options)
nm = NmapProcess(targets, options, event_callback=status_callback)
rc = nm.sudo_run()
if rc == 0 and nm.stdout:
r = nm.stdout
else:
r = None
return r
示例4: nmap_scan
def nmap_scan(hosts):
'''
Do Nmap scan
'''
# -sV is included by default in NmapProcess nmap cmd
# To add more: options = '-T4 -sU -p-'
# hosts = ['192.168.0.1', '192.168.0.2']
#nmap_args = '-T4 -sV -sS -pU:161,137,139'# -sS -sU --top-ports'
nmap_args = '-T4 -sS -sV --max-rtt-timeout 150ms --max-retries 3'
print '[*] Running: nmap {0} -iL <hostlist>'.format(nmap_args)
nmap_proc = NmapProcess(targets=hosts, options=nmap_args)
#rc = nmap_proc.sudo_run()
rc = nmap_proc.sudo_run_background()
while nmap_proc.is_running():
print("[*] Nmap progress: {1}%".format(nmap_proc.etc, nmap_proc.progress))
time.sleep(2)
xml = nmap_proc.stdout
try:
report = NmapParser.parse(nmap_proc.stdout)
except NmapParserException as e:
print 'Exception raised while parsing scan: {0}'.format(e.msg)
sys.exit()
return report
示例5: do_scan
def do_scan(targets,options):
parsed = None
proc = NmapProcess(targets,options)
running = proc.run()
if running != 0:
raise Exception("Scan failed")
return NmapParser.parse(proc.stdout)
示例6: nmap_os_services_scan
def nmap_os_services_scan(self, target, portlist=None, version_intense = 0):
'''
Runs
Arguments:
- ``target``: IP or the range of IPs that need to be tested
- ``portlist``: list of ports, range of ports that need to be tested. They can either be comma separated or separated by hyphen
example: 121,161,240 or 1-100
- ``version_intense``: Version intensity of OS detection
Examples:
| nmap os services scan | target | portlist | version_intense |
'''
target = str(target)
if portlist:
nmap_proc_cmd = "-Pn -sV --version-intensity {0} -p {1}".format(portlist, version_intense)
else:
nmap_proc_cmd = "-Pn -sV --version-intensity {0}".format(portlist)
nmproc = NmapProcess(target, nmap_proc_cmd)
rc = nmproc.run()
if rc != 0:
raise Exception('EXCEPTION: nmap scan failed: {0}'.format(nmproc.stderr))
try:
parsed = NmapParser.parse(nmproc.stdout)
print parsed
self.results = parsed
except NmapParserException as ne:
print 'EXCEPTION: Exception in parsing results: {0}'.format(ne.msg)
示例7: getC
def getC(self,ip=None,config=None):
try:
if ip==None:
ip=self.ip
count={}
ip=ip+"/24"
ops="-open -p%s"
getops=ops%config
nm=NmapProcess(ip,options=getops)
ps=nm.run()
parsed=NmapParser.parse(nm.stdout)
for host in parsed.hosts:
count[host.address]=[host.address]
for serv in host.services:
if len(serv.cpelist)>1:
count[host.address].append(serv.service+":"+str(serv.port)+":"+serv.cpelist[0])
else:
count[host.address].append(serv.service+":"+str(serv.port))
return count
except Exception,e:
print e
return []
示例8: celery_nmap_scan
def celery_nmap_scan(targets, options):
"""celery_nmap_scan task"""
def status_callback(nmapscan=None):
"""status callback"""
try:
current_task.update_state(state="PROGRESS",
meta={"done": nmapscan.progress,
"etc": nmapscan.etc})
except Exception as e:
print("status_callback error: " + str(e))
nm = NmapProcess(targets, options, event_callback=status_callback)
rc = nm.run()
if rc == 0 and nm.stdout:
r = nm.stdout
# scan is finished. Now call task to insert Report into persistent db
celery_nmap_store_report.delay(task_id=celery_nmap_scan.request.id)
else:
r = None
return {"rc": rc, "report": r}
示例9: _update_info
def _update_info(self):
""" Scans the network for devices.
Returns boolean if scanning successful. """
if not self.success_init:
return False
_LOGGER.info("Scanning")
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))
nmap = NmapProcess(targets=self.hosts, options=options)
nmap.run()
if nmap.rc == 0:
if self._parse_results(nmap.stdout):
self.last_results.extend(exclude_targets)
else:
self.last_results = []
_LOGGER.error(nmap.stderr)
return False
示例10: consume
def consume(self, targets):
print(targets)
nm = NmapProcess(targets, options='-v -sn')
rc = nm.run()
try:
parsed = NmapParser.parse(nm.stdout)
except NmapParserException as e:
print("Exception raised while parsing scan: %s" % (e.msg))
HOST_UP = 1
HOST_DOWN = 0
scans = Table('host_up', connection=self.dynamo)
with scans.batch_write() as batch:
for host in parsed.hosts:
# Insert into database and delete from queue
if (host.status == 'down'):
status = 0
elif (host.status == 'up'):
status = 1
else:
status = -1
batch.put_item(data={
'ip': host.address,
'status': status,
'datetime': int(time.time())
})
示例11: _process
def _process(self, session):
nmproc = NmapProcess("10.0.0.1", "-sT")
parsed = None
rc = nmproc.run()
if rc != 0:
logging.critical("NMAP Scan failed: {0}".format(nmproc.stderr))
try:
parsed = NmapParser.parse(nmproc.stdout)
except NmapParserException as e:
logging.critical("NMAP Parse failed: {0}".format(e.msg))
if parsed is not None:
for host in parsed.hosts:
if len(host.hostnames):
tmp_host = host.hostnames.pop()
else:
tmp_host = host.address
print("Nmap scan report for {0} ({1})".format(tmp_host, host.address))
print("Host is {0}.".format(host.status))
print(" PORT STATE SERVICE")
for serv in host.services:
pserv = "{0:>5s}/{1:3s} {2:12s} {3}".format(
str(serv.port), serv.protocol, serv.state, serv.service
)
if len(serv.banner):
pserv += " ({0})".format(serv.banner)
print(pserv)
示例12: portScan
def portScan():
global parsed
print"Scanning ports: %s" %ports
nm = NmapProcess(args.target, options="-sS -n -T4 -p%s" %ports)
rc = nm.run()
if rc != 0:
print("nmap scan failed: {0}".format(nm.stderr))
parsed = NmapParser.parse(nm.stdout)
示例13: worker
def worker(q, lock, percent, pingtype):
'''
Create Nmap processes to ping sweep each subnet then add a percentage
of the hosts that are up to the master sample list
'''
for netblock in iter(q.get, 'STOP'):
if pingtype == 'portscan':
nmap_args = '--top-ports 5 --max-rtt-timeout 150ms --max-retries 3'
elif pingtype == 'arpscan':
nmap_args = '-T4 -sn --max-rtt-timeout 150ms --max-retries 3'
else:
nmap_args = '-T4 -PE -sn --max-rtt-timeout 150ms --max-retries 3'
print '[*] nmap {0} {1}'.format(nmap_args, netblock)
nmap_proc = NmapProcess(targets=netblock, options=nmap_args)
rc = nmap_proc.run()
xml = nmap_proc.stdout
try:
report = NmapParser.parse(xml)
except NmapParserException as e:
print 'Exception raised while parsing scan: {0}'.format(e.msg)
continue
subnet_hosts_up = []
for host in report.hosts:
if host.is_up():
ip = host.address
hostname = None
if len(host.hostnames) != 0:
hostname = host.hostnames[0]
if pingtype == 'portscan':
for s in host.services:
if re.search('open|filtered', s.state):
subnet_hosts_up.append(ip)
break
else:
subnet_hosts_up.append(ip)
num_hosts = float(len(subnet_hosts_up))
random_sample_num = int(ceil(num_hosts * percent))
sample = []
for i in xrange(random_sample_num):
s = random.choice(subnet_hosts_up)
sample.append(s)
if len(sample) > 0:
print '[+] Random {0}% of live hosts in subnet {1}:'.format(percent*100, netblock)
for ip in sample:
print ' ', ip
if len(sample) > 0:
with lock:
with open('SampleIPs.txt', 'a+') as f:
for ip in sample:
f.write(ip+'\n')
示例14: is_alive
def is_alive(self):
self.alive = False
nmproc = NmapProcess(str(self.ip), '-sn')
rc = nmproc.run()
if rc != 0:
self.has_error("(alive) {}".format(nmproc.stderr))
else:
nmap_report = NmapParser.parse(nmproc.stdout)
self.alive = (nmap_report.hosts[0].status == 'up')
示例15: nmap_scan
def nmap_scan(targets, options):
nm = NmapProcess(targets, options)
rc = nm.run()
if nm.rc == 0:
return nm.stdout
else:
return nm.stderr