Exemple #1
0
    def targets(self):
        if not self._targets:

#            cc = AvrGcc()
#            cc.optimize_no()
#            cc.mcu = 'xxxx'
#            try:
#                cc.build(self.minprog)
#            except AvrGccCompileError:
#                pass
#            lines = cc.error_text.splitlines()
#            lines = [x for x in lines if '/' not in x]
#            lines = [x for x in lines if ':' not in x]
#            lines = [x for x in lines if 'xxxx' not in x]
#            lines = [x for x in lines if '\\' not in x]
#            lines = [x.strip() for x in lines]
#            lines.sort()
#            self._targets = lines
            def filt1(lines):
                for i, x in enumerate(lines):
                    if 'known mcu names' in x.lower():
                        return lines[i + 1:]

            def filt2(lines):
                for i, x in enumerate(lines):
                    if not x:
                        return lines[:i]

            s = Proc([self.cc, '--target-help']).call().stdout
            lines = s.splitlines()
            lines = filt1(lines)
            lines = filt2(lines)
            mcus = ' '.join(lines).strip().split()
            self._targets = mcus
        return self._targets
Exemple #2
0
 def scan_channels(self, dvbsource):
     """
     Executa o processo de DVB para buscar os canais contidos no fluxo
     retorna a lista de canais encontrados
     """
     cmd = []
     from django.conf import settings
     dvb = settings.DVBLAST_COMMAND
     dvbsource.record_config()
     cmd.append(dvb)
     if dvbsource.hardware_id is not None:
         dev = dvbsource.get_adapter()
         if dev >= 0:
             cmd.append('-a %d' % dev)
     cmd.append('-c %s/channels.d/%s.conf' %
                (settings.DVBLAST_CONF_DIR, dvbsource.id))
     device = '%s' % dvbsource.device
     cmd.append(device)
     scmd = ' '.join(cmd)
     from easyprocess import Proc
     proc = Proc(scmd).call(timeout=8)
     #stdout=proc.stdout
     stdout = proc.stderr
     ret = parse_dvb(stdout, debug=True)
     if proc.is_alive():
         proc.stop()
     return ret
Exemple #3
0
    def targets(self):
        if not self._targets:

#            cc = AvrGcc()
#            cc.optimize_no()
#            cc.mcu = 'xxxx'
#            try:
#                cc.build(self.minprog)
#            except AvrGccCompileError:
#                pass
#            lines = cc.error_text.splitlines()
#            lines = [x for x in lines if '/' not in x]
#            lines = [x for x in lines if ':' not in x]
#            lines = [x for x in lines if 'xxxx' not in x]
#            lines = [x for x in lines if '\\' not in x]
#            lines = [x.strip() for x in lines]
#            lines.sort()
#            self._targets = lines
            def filt1(lines):
                for i, x in enumerate(lines):
                    if 'known mcu names' in x.lower():
                        return lines[i + 1:]

            def filt2(lines):
                for i, x in enumerate(lines):
                    if not x:
                        return lines[:i]

            s = Proc([self.cc, '--target-help']).call().stdout
            lines = s.splitlines()
            lines = filt1(lines)
            lines = filt2(lines)
            mcus = ' '.join(lines).strip().split()
            self._targets = mcus
        return self._targets
Exemple #4
0
def dow3af(fn, host):
    st = '''

# -----------------------------------------------------------------------------------------------------------
#                                              W3AF AUDIT SCRIPT FOR WEB APPLICATION
# -----------------------------------------------------------------------------------------------------------
#Configure HTTP settings
http-settings
set timeout 10
#set headers_file cookie.txt
back

#Configure scanner global behaviors
misc-settings
set max_discovery_time 20
set fuzz_url_parts True
set fuzz_url_filenames True
back

plugins

#Configure entry point (CRAWLING) scanner
crawl web_spider
crawl config web_spider
set only_forward True
#set ignore_regex (?i)(logout|disconnect|signout|exit)+
set ignore_regex .*(logout|disconnect|signout|exit).*
back


#Configure reporting in order to generate an HTML report
output console

output config console
set verbose False
back

back
#Set target informations, do a cleanup and run the scan
target 
set target {0}
back

cleanup
start
exit'''.format(host)
    tmpfn = fn[fn.rfind('/') + 1:]
    open("/tmp/%s.w3af" % tmpfn, 'wb').write(st)
    #print 'w3af -s /tmp/%s.w3af | tee %s' % (tmpfn, fn)
    stdout = Proc("bash w3af.sh '/tmp/%s.w3af' '%s'" %
                  (tmpfn, fn)).call(timeout=30).stdout
    os.remove("/tmp/%s.w3af" % tmpfn)
    return fn


#getcookie('http://192.168.200.1/DVWA/login.php', 'admin', 'password')

#print Proc('echo 123 ').call(timeout=10).stdout
#dow3af("dkm.txt", "https://risks.solutions/")
#print "DONE"
Exemple #5
0
def take_photo(timeout, logger):
    cmd = '/usr/bin/fswebcam -q -d /dev/video0  -r 800x600 --no-banner  --set "Exposure, Auto"="Manual Mode" --set "Exposure (Absolute)"=200 --set brightness=50% --set "Exposure, Auto Priority"="False" meter.jpg'
    proc = Proc(cmd).call(timeout=timeout)
    #print proc.stdout
    if proc.stderr:
        logger.warning(proc.stderr)
    return proc.return_code
Exemple #6
0
def take_photo(timeout,logger):
    # will almost certainly need adjusting for your setup
    cmd = '/usr/bin/fswebcam -q -d /dev/video0  -r 800x600 --no-banner  --set "Exposure, Auto"="Manual Mode" --set "Exposure (Absolute)"=200 --set brightness=50% --set "Exposure, Auto Priority"="False" ' + image_file
    proc=Proc(cmd).call(timeout=timeout)
    if proc.stderr:
        logger.warning(proc.stderr)
    return proc.return_code
Exemple #7
0
    def test2(self):
        d = tempfile.mkdtemp()
        x_txt = os.path.join(d, 'x.txt')
        open(x_txt, 'w').write('123')
        x_zip = os.path.join(d, 'x.zip')
        Proc(['zip', '--no-dir-entries', x_zip, 'x.txt'], cwd=d).call()

        self.assertRaises(ValueError,
                          lambda: Archive(x_zip).extractall('blabla'))

        d = tempfile.mkdtemp()
        Archive(x_zip, backend='patool').extractall(d)
        ok_file(d, 'x.txt')

        d = tempfile.mkdtemp()
        Archive(x_zip).extractall(d)
        ok_file(d, 'x.txt')

        d = tempfile.mkdtemp()
        Archive(x_zip, backend='auto').extractall(d)
        ok_file(d, 'x.txt')

        if sys.version_info >= (2, 6):
            d = tempfile.mkdtemp()
            Archive(x_zip, backend='zipfile').extractall(d)
            ok_file(d, 'x.txt')

        d = tempfile.mkdtemp()
        cli.extractall(x_zip, d)
        ok_file(d, 'x.txt')
Exemple #8
0
    def build(self, sources=None, headers=None):
        ''' sources can be file name or code:
        sources=['x.c','int main(){}']
        or
        sources='int main(){}'
        '''
        tempdir = None
        strings, files = separate_sources(sources)
        if len(strings) or headers:
            # TODO: remove tempdir
            tempdir = tmpdir()

        temp_list = [tmpfile(x, tempdir, '.c') for x in strings]

        if headers:
            for n, s in headers.items():
                (Path(tempdir) / n).write_text(s)

        cmd = self.command_list(files + temp_list)
        if tempdir:
            cmd += ['-I' + tempdir]
        self.proc = Proc(cmd).call()
#        for x in temp_list:
#            os.remove(x)

        if not self.ok:
            raise AvrGccCompileError(cmd, sources, self.error_text)
Exemple #9
0
def RelPrint_WithPriv(file, deps_to_remove):
    deps = ""
    for s in deps_to_remove:
       deps = deps + str(s) + ","
    deps = deps[:-1]
    cmd = path_framework + " " + file + " --relation_print --silent=1 --no_sources --rem_deps=" + deps
    print cmd
    return Proc(cmd).call(timeout=3600).stdout
Exemple #10
0
    def run(self, objfile, mcu):

        objfile = Path(objfile).abspath()
        if not objfile.exists():
            raise AvrSizeError('no hex file! ' + objfile)
        cmd = 'avr-size --format=avr --mcu={mcu} {objfile}'.format(
            objfile=objfile, mcu=mcu)
        p = Proc(cmd).call()
        self.parse_output(p.stdout)
Exemple #11
0
 def extractall_patool(self, directory, patool_path):
     log.debug("starting backend patool")
     p = Proc([
         patool_path,
         'extract',
         self.filename,
         '--outdir=' + directory,
         #                     '--verbose',
     ]).call()
     if p.return_code:
         raise PatoolError("patool can not unpack\n" + str(p.stderr))
Exemple #12
0
 def direct_play(self, channel, ip, port, seek):
     ## Por hora mata o processo anterior e inicia um novo com os parametros
     for proc in self.list_running():
         if proc['command'].find(ip) > 0:
             os.kill(proc['pid'], signal.SIGKILL)
     fps = 27000000
     delta = seek * fps
     cmd = []
     cmd.append(self._playerapp)
     cmd.append('-u')
     cmd.append('-U')
     cmd.append('-k -%d' % delta)
     origem = '%s' % (channel)
     destino = '%s:%s' % (ip, port)
     cmd.append(origem)
     cmd.append(destino)
     scmd = ' '.join(cmd)
     from easyprocess import Proc
     stdout = Proc(scmd).call().stdout
     pid_ret = int(stdout.strip())
     return pid_ret
Exemple #13
0
 def play_source(self, dvbsource):
     """
     Inicia um processo de dvblast com o fluxo (stream)
     retorna pid
     """
     cmd = []
     from django.conf import settings
     dvb = settings.DVBLAST_DAEMON
     dvbsource.record_config()
     cmd.append(dvb)
     if dvbsource.hardware_id is not None:
         dev = dvbsource.get_adapter()
         if dev >= 0:
             cmd.append('-a %d' % dev)
     cmd.append('-c %s/channels.d/%s.conf' %
                (settings.DVBLAST_CONF_DIR, dvbsource.id))
     device = '%s' % dvbsource.device
     cmd.append(device)
     scmd = ' '.join(cmd)
     from easyprocess import Proc
     stdout = Proc(scmd).call().stdout
     pid_ret = int(stdout.strip())
     return pid_ret
Exemple #14
0
    def run_command(self, cmd):
        self.logger.info("waiting %d seconds for process" % self.timeout)
        self.logger.debug(cmd)

        # run with easyprocess
        proc=Proc(cmd).call(timeout=self.timeout)

        if proc.return_code == 0:
            self.logger.info("success")
            return proc.stdout
        elif proc.return_code == -15:
            # timed out
            raise WB_Exception("gatttool timed out")
        else:
            # an error?
            raise WB_Exception("gatttool returned error: %s" % proc.stderr)
Exemple #15
0
    def build_ino(self, sources=None):
        # TODO: remove tempdir
        tempdir = tmpdir(dir=tmpdir())
        lib = tempdir / 'lib'
        src = tempdir / 'src'
        build = tempdir / '.build'
        lib.mkdir()
        src.mkdir()

        self.setup_sources(src, sources)
        cmd = self.command_list()

        self.proc = Proc(cmd, cwd=tempdir).call()
        if not self.ok:
            raise ArduinoCompileError(cmd, sources, self.error_text)
        self.output = build.walkfiles('*.elf')[0]
Exemple #16
0
    def build_arscons(self, sources=None):
        # TODO: remove tempdir
        tempdir = tmpdir(dir=tmpdir())

        SConstruct = Path(__file__).parent / 'SConstruct'
        SConstruct.copy(tempdir / 'SConstruct')

        allfiles = self.setup_sources(tempdir, sources)
        projname = self.guess_projname(allfiles)
        tempdir = rename(tempdir, tempdir.parent / projname)
        cmd = self.command_list()

        self.proc = Proc(cmd, cwd=tempdir).call()
        if not self.ok:
            raise ArduinoCompileError(cmd, sources, self.error_text)
        self.output = tempdir.files('*.elf')[0]
Exemple #17
0
def RelPrint(file, only_tiling=0):
    cmd = path_framework + " " + file + " --relation_print --silent=1" 
    if only_tiling==1:
        cmd = cmd + " --no_sources=1" 
    print cmd
    return Proc(cmd).call(timeout=25).stdout
Exemple #18
0
def Gen(file_C, _scc, permute):
    # wywolaj esys


    z = 0
    with open("tmp/geo.txt") as f:
        content = f.readlines()
        z = len(content)
    
    Tile = False
    if len(tile_stuff) > 0:
        Tile = True
        
    if Tile:
        l = []
        for i in range(0, z):
            l.append(i)
        p = Pool(z)
        p.map(Tile_loop, l)
        
    for i in range(0, z):
        inp = "tmp/petit_loop_" + str(i) + ".t"
        LD_inp = "tmp/LD_petit_loop_" + str(i) + ".t"
        IND_loop = "tmp/IND_petit_loop_" + str(i) + ".t"
        outp = "tmp/C_output_" + str(i) + ".c"
        source_loop = "tmp/C_loop_" + str(i) + ".c"
        
        
        #tile
        if(Tile) > 0:
            #tiling_v3.tile(source_loop, tile_stuff[0], tile_stuff[1], outp)
            continue
       
        
        # zapisz zaleznosci w pliku desp.txt
        cmd = path_petit + " " + inp + " > tmp/deps"+str(i)+".txt"
        process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        process.wait()
        
        # dopisz spmd.c
        cmd = path_petit + " -W " + inp
        process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process.wait()

        # zapisz zaleznosci w pliku _desp.txt dla tewi
        cmd = path_petit + " -b " + inp + " > tmp/_deps"+str(i)+".txt"
        process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
        process.wait()
        
        if _scc==1:
            scc.GenerateSCC(i, permute)
            sys.exit() 
            
        scc.DepGraph(i)
        
        
        priv_stuff = priv_engine.PrivEng("tmp/deps"+str(i)+".txt")
        #print "tmp/deps"+str(i)+".txt"
        #remove deps
        _str = ''
        #print priv_stuff
        if len(priv_stuff[1]) > 0: 
            _str = " --rem_deps="
            for v in priv_stuff[1]:
                _str = _str + str(v) + ","                 
            _str = _str[:-1]

        reduce_op = reduce.Reduction("tmp/deps"+str(i)+".txt")
        if((reduce_op == '' and priv_stuff[2] == 0) or PAR_ALWAYS):     # no par, use framework
            
            # IND Loop
            try:
                IND_Gen(inp, LD_inp, IND_loop)
            except:
                print 'IND loop was not calculated'

            # PARALLELIZE LOOPS
            
            cmd = path_framework + " " + inp + " " + out_command + outp + " " + silent_mode + " --fs_pragma=" + rpath + " " + _str + " --ind_loop=" + IND_loop    
            #process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)
            #process.wait()
            stdout=Proc(cmd).call(timeout=5).stdout
            
            fo = open("tmp/debug.txt", "at")
            fo.write(stdout.encode('ascii', 'ignore'))
            fo.close()
        else:
            _file = open(outp, 'w')
            _file.write("#pragma omp parallel for")
            _file.close()

        

        
        
        if os.path.exists("tmp/C_output_" + str(i) + ".c"):
            
            # gdy nie ma zaleznosci
            file = open("tmp/C_output_" + str(i) + ".c", 'r')
            lines = file.readlines()
            file.close()
            
            if len(lines) == 1 and "#pragma" in lines[0]:
                file = open("tmp/C_loop_" + str(i) + ".c", 'r')
                lines2 = file.readlines()
                file.close()
                
                file = open("tmp/C_output_" + str(i) + ".c", 'w')
                lines[0] = lines[0] +"\n"
                file.writelines(lines)
                file.writelines(lines2)
                file.close()
            # --------------------
            
            #sprawdz czy nie ma samej pragmy jak tak to skopiuj pliki dodaj pragmy z private
            CorrectFile("tmp/C_output_" + str(i) + ".c", priv_stuff[0], reduce_op)  
            loop_tools.CorrectLoop("tmp/C_output_" + str(i) + ".c") 
        else:
            parfine.ParInner(i);
    
    # wywolaj output_gen
    output_gen.Output_Gen(file_C, Tile)
Exemple #19
0
def IND_Gen(inp, LD_inp, IND_loop):
 #LD IND LOOP
    line_r=Proc(path_framework + " " + inp + " --return=1 " +  silent_mode ).call(timeout=5).stdout
    line_ld=Proc(path_framework + " " + LD_inp + " --return=1 " +  silent_mode ).call(timeout=5).stdout
    #line_r = line_r.replace("\n", "")
    line_ld = line_ld.replace("\n", "")
    
#    fo = open("tmp/debug.txt", "wt")
#    fo.write(line_r);
#    fo.close()

    
    symb = ""
    if("Sym" in line_r):
        pattern = re.compile('Sym=.[^\]]*')
        symb = pattern.findall(line_r)
       # print symb
        symb =  symb[0].replace("Sym=[", "")
        
  #  print symb
        
    script_lines = []
    if(symb != ""):
        script_lines.append("symbolic " + symb + ";")
    
    #pattern = re.compile('====.*$')
    #RSPACE = pattern.findall(line_r)
    rss = line_r.split('====')[1]
    ldd = line_ld.split('====')[1]


    script_lines.append("RS := " + rss + ";")

    LD = pattern.findall(line_ld)
  #  print LD
    
    script_lines.append("LD := " + ldd + ";")
    script_lines.append("RS_S := domain RS union range RS;")
    script_lines.append("LD_S := domain LD union range LD;")
    script_lines.append("codegen LD_S - RS_S;")
    
    thefile = open("tmp/ld_script_oc", 'w')
    for item in script_lines:
        thefile.write("%s\n" % item)
    thefile.close();  
    
    output = Proc(path_oc + " " + "tmp/ld_script_oc").call(timeout=5).stdout
    
    output = output.split("\n")
    output2 = []
    was =0
    for item in output:
        if len(item) > 0: 
            if(item[0] != '#'):
                if('for' in item and was == 0):
                    output2.append("#pragma omp parallel for")
                    was = 1
                if not item.isspace():   # nie zapisuj pustych linii
                    output2.append(item)

    if(len(output2) > 0):   # jesli jest co zapisac IND
        thefile = open(IND_loop, 'w')
        for item in output2:
            thefile.write("%s\n" % item)
        thefile.close();         
Exemple #20
0
def ParsePrint2(file, z):
    cmd = path_framework + " " + file + " --parse_print="+str(z)+" --silent=1"    
    return Proc(cmd).call(timeout=5).stdout
Exemple #21
0
def Petit_Rel(file):
    cmd = path_petit_rel + " " + file
    return Proc(cmd).call(timeout=5).stdout
Exemple #22
0
 def version(self):
     'avr-gcc version'
     return extract_version(Proc(self.cc + ' --version').call().stdout)