本文整理汇总了Python中libnmap.process.NmapProcess.run_background方法的典型用法代码示例。如果您正苦于以下问题:Python NmapProcess.run_background方法的具体用法?Python NmapProcess.run_background怎么用?Python NmapProcess.run_background使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类libnmap.process.NmapProcess
的用法示例。
在下文中一共展示了NmapProcess.run_background方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: run_nmap_scan
# 需要导入模块: from libnmap.process import NmapProcess [as 别名]
# 或者: from libnmap.process.NmapProcess import run_background [as 别名]
def run_nmap_scan(scan_targets, scan_options):
'''
Accepts scan targets and scan options for NmapProcess and launches scan
Prints scan status updates and summary to stdout
Returns NmapProcess object for further use
TODO - catch keyboard interrupts and kill tasks so we can exit gracefully!
nmap_proc.stop does not appear to fully kill threads in script scans
so program will continue to execute but leaves an orphaned nmap process
'''
status_update_interval = 5
#Check for sudo and disable scan options that require root
if os.getuid()!=0:
logging.warn("Certain nmap scans require root privileges (SYN, UDP, ICMP, etc)...")
logging.warn("Disabling incompatible scan types and OS / service version detection options if enabled")
scan_options = scan_options.replace("-sS", "-sT")
scan_options = scan_options.replace("-sU", "")
scan_options = scan_options.replace("-sP", "")
scan_options = scan_options.replace("-sn", "")
scan_options = scan_options.replace("-sV", "")
scan_options = scan_options.replace("-O", "")
nmap_proc = NmapProcess(targets=scan_targets, options=scan_options)
print "Running scan command:\n"+nmap_proc.command
nmap_proc.run_background()
while nmap_proc.is_running():
try:
time.sleep(status_update_interval)
if nmap_proc.progress > 0:
#Nmap only updates ETC periodically and will sometimes return a result that is behind current system time
etctime = datetime.datetime.fromtimestamp(int(nmap_proc.etc))
systime = datetime.datetime.now().replace(microsecond=0)
if etctime < systime:
etctime = systime
timeleft = etctime - systime
print("{0} Timing: About {1}% done; ETC: {2} ({3} remaining)".format(nmap_proc.current_task.name, nmap_proc.progress, etctime, timeleft))
except KeyboardInterrupt:
print "Keyboard Interrupt - Killing Current Nmap Scan!"
nmap_proc.stop()
if nmap_proc.rc == 0:
print nmap_proc.summary + "\n"
else:
print nmap_proc.stderr + "\n"
return nmap_proc
示例2: do_scan
# 需要导入模块: from libnmap.process import NmapProcess [as 别名]
# 或者: from libnmap.process.NmapProcess import run_background [as 别名]
def do_scan(self):
"""scan start flag"""
if(self._flg_is_scanning != True):
self._flg_is_scanning = True
if(self._flg_scan_finished != False):
self._flg_scan_finished = False
"""运行次数初始化"""
trycnt = 0
while True:
"""运行时间初始化"""
runtime = 0
if trycnt >= self.retrycnt:
print '-' * 50
return 'retry overflow'
try:
nmap_proc = NmapProcess(targets=self.targets,options=self.options,safe_mode=False)
self._flg_is_scanning = True
nmap_proc.run_background()
while(nmap_proc.is_running()):
"""运行超时,结束掉任务,休息1分钟,再重启这个nmap任务"""
if runtime >= self.timeout:
print '-' * 50
print "timeout....terminate it...."
nmap_proc.stop()
"""休眠时间"""
sleep(60)
trycnt += 1
break
else:
print 'running[%ss]:%s' %(runtime,nmap_proc.command)
sleep(5)
runtime += 5
if nmap_proc.is_successful():
"""scan finished flag"""
if(self._flg_is_scanning != False):
self._flg_is_scanning = False
if(self._flg_scan_finished != True):
self._flg_scan_finished = True
print '-' * 50
print nmap_proc.summary
return nmap_proc.stdout
except Exception,e:
print e
trycnt +=1
if trycnt >= retrycnt:
print '-' * 50
print 'retry overflow'
return e
示例3: do_nmap_scan
# 需要导入模块: from libnmap.process import NmapProcess [as 别名]
# 或者: from libnmap.process.NmapProcess import run_background [as 别名]
def do_nmap_scan(targets, options=global_options):
# 运行次数初始化
trycnt = 0
while True:
# 运行时间初始化
runtime = 0
if trycnt >= retrycnt:
print '-' * 50
return 'retry overflow'
try:
nmap_proc = NmapProcess(targets=targets, options=options, safe_mode=False)
nmap_proc.run_background()
while nmap_proc.is_running():
if runtime >= timeout: # 运行超时,结束掉任务,休息1分钟, 再重启这个nmap任务
print '-' * 50
print "* timeout. terminate it..."
nmap_proc.stop()
# 休眠时间
sleep(60)
trycnt += 1
break
else:
print 'running[%ss]:%s' % (runtime, nmap_proc.command)
sleep(5)
runtime += 5
if nmap_proc.is_successful():
print '-' * 50
print nmap_proc.summary
return nmap_proc.stdout
except Exception, e:
# raise e
print e
trycnt += 1
if trycnt >= retrycnt:
print '-' * 50
print '* retry overflow'
return e
示例4: scan_host
# 需要导入模块: from libnmap.process import NmapProcess [as 别名]
# 或者: from libnmap.process.NmapProcess import run_background [as 别名]
def scan_host(target_host, num_tries):
nm = NmapProcess(target_host, options='-sT -Pn -T3')
cur_try = 0
while cur_try < num_tries:
logger.debug(
"Now running scan attempt #%d for host at %s."
% (cur_try + 1, target_host)
)
result = nm.run_background()
while nm.is_running():
logger.debug(
"Scan running. ETC: %s. DONE: %s."
% (nm.etc, nm.progress)
)
sleep(2)
if nm.rc != 0:
logger.warning(
"Scan #%d for host at %s failed!"
% (cur_try + 1, target_host)
)
cur_try += 1
else:
logger.debug(
"Scan for host at %s succeeded!"
% (target_host,)
)
break
if str(nm.state) != str(nm.DONE):
logger.warning(
"Scan for host at %s failed!"
% (target_host,)
)
return
else:
try:
parsed = NmapParser.parse(nm.stdout)
except NmapParserException as e:
logger.error(
"NmapParserException thrown: %s."
% (e.msg,)
)
host = parsed.hosts[0]
to_return = []
for service in host.services:
to_return.append(
"%s//%s//%s//%s"
% (
host.ipv4,
service.protocol,
str(service.port),
service.state
)
)
return to_return
示例5: do_nmap_scan
# 需要导入模块: from libnmap.process import NmapProcess [as 别名]
# 或者: from libnmap.process.NmapProcess import run_background [as 别名]
def do_nmap_scan(targets, options=NMAP_GLOBAL_OPTIONS):
# 运行次数初始化
trycnt = 0
while True:
# 运行时间初始化
runtime = 0
if trycnt >= NMAP_RETRYCNT:
print "-" * 50
return "retry overflow"
try:
nmap_proc = NmapProcess(targets=targets, options=options, safe_mode=False)
nmap_proc.run_background()
while nmap_proc.is_running():
if runtime >= NMAP_TIMEOUT: # 运行超时,结束掉任务,休息1分钟, 再重启这个nmap任务
print "-" * 50
print "* timeout. terminate it..."
nmap_proc.stop()
# 休眠时间
time.sleep(60)
trycnt += 1
break
else:
print "running[%ss]:%s" % (runtime, nmap_proc.command)
time.sleep(5)
runtime += 5
if nmap_proc.rc == 0:
return nmap_proc.stdout
except Exception, e:
# raise e
print e
trycnt += 1
if trycnt >= NMAP_RETRYCNT:
print "-" * 50
print "* retry overflow"
return e
示例6: ScanEngine
# 需要导入模块: from libnmap.process import NmapProcess [as 别名]
# 或者: from libnmap.process.NmapProcess import run_background [as 别名]
class ScanEngine(object):
def __init__(self,config):
self.engine = NmapProcess(config.targets, config.options)
def run(self):
"""Execute scan"""
syslog.syslog("Starting scan")
self.engine.run_background()
while self.engine.is_running():
time.sleep(15)
print "Scan is %s percent complete" % self.engine.progress
syslog.syslog("Completed scan")
def process(self):
"""parse and pre-process scan results"""
try:
self.parsed = NmapParser.parse(self.engine.stdout)
syslog.syslog("Processing output")
except Exception as e:
syslog.syslog("Failed to parse output"+e)
for h in self.parsed.hosts:
print h.address
示例7: do_scan
# 需要导入模块: from libnmap.process import NmapProcess [as 别名]
# 或者: from libnmap.process.NmapProcess import run_background [as 别名]
def do_scan(targets, options):
parsed = None
nmproc = NmapProcess(targets, options)
rc = nmproc.run_background()
while nmproc.is_running():
print("Nmap Scan is running: ETC: {0} DONE: {1}%".format(nmproc.etc, nmproc.progress))
sleep(2)
print("rc: {0} output: {1}".format(nmproc.rc, nmproc.summary))
if rc != 0:
print("nmap scan failed: {0}".format(nmproc.stderr))
print(type(nmproc.stdout))
try:
parsed = NmapParser.parse(nmproc.stdout)
except NmapParserException as e:
print("Exception raised while parsing scan: {0}".format(e.msg))
return parsed
示例8: NmapProcess
# 需要导入模块: from libnmap.process import NmapProcess [as 别名]
# 或者: from libnmap.process.NmapProcess import run_background [as 别名]
#!/usr/bin/env python
from libnmap.process import NmapProcess
from time import sleep
nmap_proc = NmapProcess(targets="scanme.nmap.org", options="-sT")
nmap_proc.run_background()
while nmap_proc.is_running():
nmaptask = nmap_proc.current_task
if nmaptask:
print "Task {0} ({1}): ETC: {2} DONE: {3}%".format(nmaptask.name,
nmaptask.status,
nmaptask.etc,
nmaptask.progress)
sleep(0.5)
print "rc: {0} output: {1}".format(nmap_proc.rc, nmap_proc.summary)
print nmap_proc.stdout
示例9: NmapScan
# 需要导入模块: from libnmap.process import NmapProcess [as 别名]
# 或者: from libnmap.process.NmapProcess import run_background [as 别名]
class NmapScan(BaseScanner):
'''
Nmap scanning class, perform a couple of nmap scans of varying intensity on the specified target and reports this back in the form of ServiceResults and a SystemResult
'''
def __init__(self, ip, directory):
'''
set params, config, etc
'''
super(self.__class__, self).__init__(ip.strip())
if(directory.endswith("/")):
outputfile = directory + ip + "."
else:
outputfile = directory + "/" + ip + "."
self.FileBase = outputfile
c = AlxConfiguration()
self.currentScan = None
self.interval = 5
self.timer = None
self.running= False
self.hasQuit = False
q = Queue()
q.put(c.getQuickScanOpts())
q.put(c.getIntermediateScanOpts())
q.put(c.getUdpScanOpts())
q.put(c.getFullScanOpts())
self.scanQueue = q
def Execute(self):
#Start nmap in different thread
if not self.running:
self.timer = threading.Timer(self.interval, self._run)
self.timer.start()
self.running = True
def Quit(self):
#print("Quitting scan against {0}...").format(self.getIP())
self.timer.cancel()
self.running = False
self.timer = None
self.hasQuit = True
def _run(self):
if(self.running):
self.running = False
self.runNmap()
if(not self.hasQuit):
self.Execute()
def runNmap(self):
#gets executed every x seconds
#check current nmap scan -> if finished then parse results and start new one, otherwise wait and report status
if not self.currentScan:
#create new scan
self.createNewScan()
else:
#report current scan status
if(self.currentScan.is_running()):
print("Nmap scan for {0} ({2}) progress: {1}%").format(self.getIP(), self.currentScan.progress, self.currentScan.options)
pass
else:
if(self.currentScan.is_successful()):
self.ParseResults(self.currentScan)
self.currentScan = None
self.createNewScan()
pass
def createNewScan(self):
if self.scanQueue and not self.scanQueue.empty():
opt = self.scanQueue.get()
ip = self.getIP()
self.currentScan = NmapProcess(targets=ip, options=opt, safe_mode=False)
self.currentScan.run_background()
else:
self.Quit()
def ParseResults(self, nmapscan):
nmap_report = NmapParser.parse(nmapscan.stdout)
hresults = []
for h in nmap_report.hosts:
#assemble host
#address, os, distance, fingerprint, status
print("Assembling host data {0} {1} {2} {3} {4}".format(h.address, h.os_fingerprint, h.distance, h.status, h.mac))
hres = SystemResult.SystemResult(h.address,h.os_fingerprint, h.distance, h.status, h.mac)
hresults.append(hres)
for s in h.services:
#add services to host
if(s.state == "open"):
serv = ServiceResult.ServiceResult(s.port, s.protocol, s.reason, s.service, s.state, s.banner)
hres.addService(serv)
print("Found service {0} {1} {2} {3}").format(s.service, s.protocol, s.state, s.banner)
self.UpdateListeners(hresults)