Python commands.getstatusoutput() Examples

The following are 30 code examples of commands.getstatusoutput(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module commands , or try the search function .
Example #1
Source File: privilege.py    From bitmask-dev with GNU General Public License v3.0 6 votes vote down vote up
def _helper_installer(action):
    if action not in ('install', 'uninstall'):
        raise Exception('Wrong action: %s' % action)

    if IS_LINUX:
        if IS_SNAP:
            log.debug('Skipping install of helpers, '
                      'snap should have done that')
            return
        cmd = 'bitmask_helpers ' + action
        if STANDALONE:
            binary_path = os.path.join(here(), "bitmask")
            cmd = "%s %s" % (binary_path, cmd)
        if os.getuid() != 0:
            cmd = 'pkexec ' + cmd
        retcode, output = commands.getstatusoutput(cmd)
        if retcode != 0:
            log.error('Error installing/uninstalling helpers: %s' % output)
            log.error('Command was: %s' % cmd)
            raise Exception('Could not install/uninstall helpers')
    else:
        raise Exception('No install mechanism for this platform') 
Example #2
Source File: download_data.py    From rgz_rcnn with MIT License 6 votes vote down vote up
def download_file(url, tgt_dir):
    if (not osp.exists(tgt_dir)):
        raise Exception("tgt_dir %s not found" % tgt_dir)
    fn = url.split('/')[-1] # hack hack hack
    full_fn = osp.join(tgt_dir, fn)
    if (osp.exists(full_fn)):
        print("%s exists already, skip downloading" % full_fn)
        return full_fn
    cmd = 'wget -O %s %s' % (full_fn, url)
    print("Downloading %s to %s" % (fn, tgt_dir))
    stt = time.time()
    status, msg = commands.getstatusoutput(cmd)
    if (status != 0):
        raise Exception("Downloading from %s failed: %s" % (url, msg))
    print("Downloading took %.3f seconds" % (time.time() - stt))
    return full_fn 
Example #3
Source File: study_os.py    From Python-notes with MIT License 6 votes vote down vote up
def shell():
    command_ls = 'ls -al /opt'
    command_docker = 'docker ps -a'

    # 使用os.system()模块
    ros = os.system(command_ls)
    print '\n\nos.system() : ', ros

    # 使用os.popen()模块
    output = os.popen(command_docker)
    result = output.read()
    print '\n\nos.popen() : ', result

    # 使用commands模块
    (status, output) = commands.getstatusoutput(command_docker)
    print '\n\ncommands : ', status, output 
Example #4
Source File: srm.py    From rucio with Apache License 2.0 6 votes vote down vote up
def connect(self):
        """
        Establishes the actual connection to the referred RSE.
        As a quick and dirty impelementation we just use this method to check if the lcg tools are available.
        If we decide to use gfal, init should be done here.

        :raises RSEAccessDenied: Cannot connect.
        """

        status, lcglscommand = getstatusoutput('which lcg-ls')
        if status:
            raise exception.RSEAccessDenied('Cannot find lcg tools')
        endpoint_basepath = self.path2pfn(self.attributes['prefix'])
        status, result = getstatusoutput('%s -vv $LCGVO -b --srm-timeout 60 -D srmv2 -l %s' % (lcglscommand, endpoint_basepath))
        if status:
            if result == '':
                raise exception.RSEAccessDenied('Endpoint not reachable. lcg-ls failed with status code %s but no further details.' % (str(status)))
            else:
                raise exception.RSEAccessDenied('Endpoint not reachable : %s' % str(result)) 
Example #5
Source File: fsclient.py    From cargo with Apache License 2.0 6 votes vote down vote up
def checkAndGetNFSMeta(self, config):
        nfsMeta = dict() 
        volPath = config["volume"]

        status, output = commands.getstatusoutput(GET_ALL_NFS_MOUNTS)
        if status != 0:
            logging.error("mount list command failed. {}".format(output))
            return codes.FAILED
        
        if output == None:
            nfsMeta["is_nfs_mounted"] = False
            return (codes.SUCCESS, nfsMeta)

        nfsList = output.split("\n")
        for nfsmount in nfsList:
            mountPoint = nfsmount.split()[2]
            if volPath in mountPoint:
                nfsMeta["is_nfs_mounted"] = True
                nfsMeta["nfs_server"] = nfsmount.split()[0].split(":")[0]
                nfsMeta["nfs_exportpath"] = nfsmount.split()[0].split(":")[1]
                nfsMeta["nfs_mountpath"] = mountPoint
                return (codes.SUCCESS, nfsMeta) 
Example #6
Source File: fsclient.py    From cargo with Apache License 2.0 6 votes vote down vote up
def nfsExport(self, config):
        dirpath = config["exportPath"]

        if not os.path.exists(dirpath):
            return codes.NOT_FOUND
        
        #exportcfg = "{path} *(rw,fsid=0,sync,no_root_squash)\n".format(path = dirpath)
        exportcfg = "{path} *(rw,sync,no_root_squash,nohide)\n".format(path = dirpath)
        fp = open(NFS_EXPORT_CONFIG, 'a')
        fp.write(exportcfg)
        fp.close()
        
        logging.debug("Re-exporting NFS mounts.")
        status, output = commands.getstatusoutput(NFS_EXPORT_FS)
        if status != 0:
            logging.error("NFS restart failed. {}".format(output))
            return codes.FAILED

        return codes.SUCCESS 
Example #7
Source File: airmode.py    From airmode with GNU General Public License v2.0 6 votes vote down vote up
def slot_monitor(self):
        
        if self.check_options(self.periferica_opt) == 0:
            pass
        
        elif self.intf_mode == "Monitor":
            status = commands.getstatusoutput('airmon-ng stop '  + self.periferica)
            if status[0] != 0:
                self.output(status[1], status[0])
            else:
                self.output("Monitor off: " + self.periferica, status[0])
        else:
            status = commands.getstatusoutput('airmon-ng check kill && echo y | airmon-ng start ' + self.periferica)
            if status[0] != 0:
                self.output(status[1], status[0])
            else:
                self.output("Monitor on: " + self.periferica, status[0])
        self.slot_reload_interfaces()

    #
    # Start Client Fragmentation Attack
    # 
Example #8
Source File: airmode.py    From airmode with GNU General Public License v2.0 6 votes vote down vote up
def run(self):

        # exec command
        print (self.command)

        # use terminal emulator?
        if self.use_term:
            commands.getstatusoutput(def_term + " -e 'bash -c \"" + self.command + "; read; \"'")
        
        else:
            commands.getstatusoutput(self.command)
            
        # callback
        if hasattr(self.callback, '__call__'):
           self.callback()

#
# Retarded Kill
# 
Example #9
Source File: airmode.py    From airmode with GNU General Public License v2.0 6 votes vote down vote up
def slot_mac_change(self):
        if self.check_options(self.change_mac_int_opt | self.change_mac_mac_opt | self.mymon_opn | self.intf_mode_opt) == 0:
            pass
        else:
            # backup of old MAC...
            commands.getstatusoutput('if [ -e ' + config_dir + '.macaddress-backup ]; then echo ""; else ifconfig ' + self.change_mac_int + ' | grep HWaddr | sed \'s/^.*HWaddr //\' > ' + config_dir + '.macaddress-backup; fi')
            status = commands.getstatusoutput('ifconfig ' + self.change_mac_int + ' down hw ether ' + self.change_mac_mac)
            if status[0] != 0:
                self.output(status[1], status[0])
                return
            status = commands.getstatusoutput('ifconfig ' + self.change_mac_int + ' up')
            if status[0] != 0:
                self.output(status[1], status[0])
                return
            self.output('Mac address of interface ' + self.change_mac_int + ' changed in ' + self.change_mac_mac, status[0])
            
    #
    # Enable ip forwarding
    # 
Example #10
Source File: airmode.py    From airmode with GNU General Public License v2.0 6 votes vote down vote up
def slot_monitor(self):
        
        if self.check_options(self.periferica_opt) == 0:
            pass
        
        elif self.intf_mode == "Monitor":
            status = commands.getstatusoutput('airmon-ng stop '  + self.periferica)
            if status[0] != 0:
                self.output(status[1], status[0])
            else:
                self.output("Monitor off: " + self.periferica, status[0])
        else:
            status = commands.getstatusoutput('airmon-ng check kill && echo y | airmon-ng start ' + self.periferica)
            if status[0] != 0:
                self.output(status[1], status[0])
            else:
                self.output("Monitor on: " + self.periferica, status[0])
        self.slot_reload_interfaces()

    #
    # Start Client Fragmentation Attack
    # 
Example #11
Source File: codesign_utils.py    From iOS-private-api-checker with GNU General Public License v2.0 6 votes vote down vote up
def codesignapp(app_path):
    """
    Get codesign informatiob included in app
    About codesign: https://developer.apple.com/legacy/library/technotes/tn2250/_index.html#//apple_ref/doc/uid/DTS40009933
    Args:
        Mach-o path
    Returns:
        the content of codesign
    """
    cmd = "/usr/bin/codesign -dvvv %s" % app_path
    out = commands.getstatusoutput(cmd)
    if out and len(out) == 2 and out[0] == 0:
        out = out[1]
    else:
        out = ''
    return out 
Example #12
Source File: airmode.py    From airmode with GNU General Public License v2.0 6 votes vote down vote up
def run(self):

        # exec command
        print (self.command)

        # use terminal emulator?
        if self.use_term:
            commands.getstatusoutput(def_term + " -e 'bash -c \"" + self.command + "; read; \"'")
        
        else:
            commands.getstatusoutput(self.command)
            
        # callback
        if hasattr(self.callback, '__call__'):
           self.callback()

#
# Retarded Kill
# 
Example #13
Source File: download_data.py    From rgz_rcnn with MIT License 5 votes vote down vote up
def check_req():
    cmd = 'wget --help'
    status, msg = commands.getstatusoutput(cmd)
    if (status != 0):
        raise Exception('wget is not installed properly') 
Example #14
Source File: test_util.py    From IRCLogParser with GNU General Public License v3.0 5 votes vote down vote up
def test_save_to_disk(self):
        util.save_to_disk(self.nicks, self.current_directory + "/data/nicksTest")
        status, output = commands.getstatusoutput(
            'cmp ' + self.current_directory + '/data/nicks ' + self.current_directory + '/data/nicksTest')
        subprocess.Popen(['rm', self.current_directory + '/data/nicksTest'])
        self.assertEqual(status, 0, "Failure to load from disk.") 
Example #15
Source File: test_util.py    From IRCLogParser with GNU General Public License v3.0 5 votes vote down vote up
def test_save_to_disk(self):
        util.save_to_disk(self.nicks, self.current_directory + "/data/nicksTest")
        status, output = commands.getstatusoutput('cmp '+ self.current_directory +'/data/nicks '+ self.current_directory+ '/data/nicksTest')
        subprocess.Popen(['rm', self.current_directory + '/data/nicksTest'])
        self.assertEqual(status, 0, "Failure to load from disk.") 
Example #16
Source File: cppyy.py    From parliament2 with Apache License 2.0 5 votes vote down vote up
def get_version():
   try:
      import commands
      stat, output = commands.getstatusoutput("root-config --version")
      if stat == 0:
         return output
   except Exception:
      pass
   # semi-sensible default in case of failure ...
   return "6.03/XY"

### PyPy has 'cppyy' builtin (if enabled, that is) 
Example #17
Source File: cpuinfo.py    From Mastering-Elasticsearch-7.0 with MIT License 5 votes vote down vote up
def getoutput(cmd, successful_status=(0,), stacklevel=1):
    try:
        status, output = getstatusoutput(cmd)
    except EnvironmentError:
        e = get_exception()
        warnings.warn(str(e), UserWarning, stacklevel=stacklevel)
        return False, ""
    if os.WIFEXITED(status) and os.WEXITSTATUS(status) in successful_status:
        return True, output
    return False, output 
Example #18
Source File: airmode.py    From airmode with GNU General Public License v2.0 5 votes vote down vote up
def init_config_dir():
    global def_term

    # check config dir
    if not os.path.exists(config_dir):
        os.mkdir(config_dir)    
        #subprocess.getstatusoutput('zenity --info --window-icon=/usr/local/buc/icons/attenzione.png --title="AirMode" --text="Hello and Thanks for using AirMode this is the first run, and ~/.airmode is now created."')

    print ('\nConfig directory OK\n')

#
# This function perform various checks
# on program load
# 
Example #19
Source File: airmode.py    From airmode with GNU General Public License v2.0 5 votes vote down vote up
def slot_random_mac(self):

        if self.check_options(self.periferica_opt) == 0:
            return

        # disable interface
        status = commands.getstatusoutput('ifconfig '  + self.periferica + ' down')
        if status[0] != 0:
            self.output(status[1], status[0])
            return
        
        # random MAC address
        status = commands.getstatusoutput('macchanger --random '  + self.periferica)
        if status[0] != 0:
            self.output(status[1], status[0])
            return

        # re-enable interface
        status = commands.getstatusoutput('ifconfig '  + self.periferica + ' up')
        if status[0] !=0:
            self.output(status[1], status[0])
            return

        self.output("MAC Address changed: " + self.periferica, status[0])
        
        self.slot_reload_interfaces()

    #
    # Select an interface
    # 
Example #20
Source File: airmode.py    From airmode with GNU General Public License v2.0 5 votes vote down vote up
def slot_gath_clean(self):
        commands.getstatusoutput('rm -f ' + config_dir + '*.cap ' + config_dir + '*.csv ' + config_dir + '*.xor ' + config_dir + '*.netxml ')
        self.direct_output('Logs cleaned')

    #
    # WPA Rainbow Tables Cracking
    # 
Example #21
Source File: airmode.py    From airmode with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        time.sleep(self.sec)
        commands.getstatusoutput("killall " + self.prog)

#
# For the callbacks function
# extend Main_window class (that contains the GUI)
# 
Example #22
Source File: cpuinfo.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def getoutput(cmd, successful_status=(0,), stacklevel=1):
    try:
        status, output = getstatusoutput(cmd)
    except EnvironmentError:
        e = get_exception()
        warnings.warn(str(e), UserWarning, stacklevel=stacklevel)
        return False, output
    if os.WIFEXITED(status) and os.WEXITSTATUS(status) in successful_status:
        return True, output
    return False, output 
Example #23
Source File: airmode.py    From airmode with GNU General Public License v2.0 5 votes vote down vote up
def init_config_dir():
    global def_term

    # check config dir
    if not os.path.exists(config_dir):
        os.mkdir(config_dir)    
        #subprocess.getstatusoutput('zenity --info --window-icon=/usr/local/buc/icons/attenzione.png --title="AirMode" --text="Hello and Thanks for using AirMode this is the first run, and ~/.airmode is now created."')

    print ('\nConfig directory OK\n')

#
# This function perform various checks
# on program load
# 
Example #24
Source File: join_status_block.py    From t-hoarder with GNU General Public License v3.0 5 votes vote down vote up
def main():
    
  #get parameters
  files_status=['counter_status.txt','talk_status.txt','loc_status.txt']

  parser = argparse.ArgumentParser(description='This script join status of block procesed')
  parser.add_argument('experiment', type=str, help='experiment name')
  parser.add_argument('--dir_in', type=str, default='./', help='Dir data input')
  parser.add_argument('--dir_out', type=str, default='./', help='Dir data output')
  args = parser.parse_args()

  dir_in=args.dir_in
  dir_out=args.dir_out
  experiment=args.experiment
  file_log='%s/%s_status.txt' % (dir_out,experiment)
  f_log=codecs.open(file_log,'w',encoding='utf-8')
  num_pack=0
  # joining counters
  joining=JoinCounters(experiment,dir_in,dir_out)
  start = datetime.datetime.fromtimestamp(time.time())
  print 'processing counters file_counters_top'
  for file_status in  files_status:
    while True:
      pack='%s/streaming_%s_%s_%s' % (dir_in,experiment,num_pack,file_status)
      (status, output) =commands.getstatusoutput('ls '+pack)
      #print status, output
      if status !=0:
        break
      joining.status(num_pack,file_status)
      print 'processed', pack
      num_pack += 1
    joining.get_status(file_status)
    num_pack=0
  stop = datetime.datetime.fromtimestamp(time.time())
  f_log.write(('total runtime\t%s\n') % (stop - start))
  f_log.close()
  exit(0) 
Example #25
Source File: airmode.py    From airmode with GNU General Public License v2.0 5 votes vote down vote up
def slot_gath_clean(self):
        commands.getstatusoutput('rm -f ' + config_dir + '*.cap ' + config_dir + '*.csv ' + config_dir + '*.xor ' + config_dir + '*.netxml ')
        self.direct_output('Logs cleaned')

    #
    # WPA Rainbow Tables Cracking
    # 
Example #26
Source File: cpuinfo.py    From pySINDy with MIT License 5 votes vote down vote up
def getoutput(cmd, successful_status=(0,), stacklevel=1):
    try:
        status, output = getstatusoutput(cmd)
    except EnvironmentError:
        e = get_exception()
        warnings.warn(str(e), UserWarning, stacklevel=stacklevel)
        return False, ""
    if os.WIFEXITED(status) and os.WEXITSTATUS(status) in successful_status:
        return True, output
    return False, output 
Example #27
Source File: airmode.py    From airmode with GNU General Public License v2.0 5 votes vote down vote up
def run(self):
        time.sleep(self.sec)
        commands.getstatusoutput("killall " + self.prog)

#
# For the callbacks function
# extend Main_window class (that contains the GUI)
# 
Example #28
Source File: spark_gce.py    From spark_gce with Apache License 2.0 5 votes vote down vote up
def enable_sudo(master,command):
	'''
	ssh_command(master,"echo \"import os\" > setuid.py ")
	ssh_command(master,"echo \"import sys\" >> setuid.py")
	ssh_command(master,"echo \"import commands\" >> setuid.py")
	ssh_command(master,"echo \"command=sys.argv[1]\" >> setuid.py")
	ssh_command(master,"echo \"os.setuid(os.geteuid())\" >> setuid.py")
	ssh_command(master,"echo \"print commands.getstatusoutput(\"command\")\" >> setuid.py")
	'''
	os.system("ssh -i " + identity_file + " -t -o 'UserKnownHostsFile=/dev/null' -o 'CheckHostIP=no' -o 'StrictHostKeyChecking no' "+ username + "@" + master + " '" + command + "'") 
Example #29
Source File: analytics.py    From alibuild with GNU General Public License v3.0 5 votes vote down vote up
def generate_analytics_id():
  getstatusoutput("mkdir -p  ~/.config/alibuild")
  err, output = getstatusoutput("uuidgen >  ~/.config/alibuild/analytics-uuid")
  # If an error is found while generating the unique user ID, we disable
  # the analytics on the machine.
  if err:
    debug("Could not generate unique ID for user. Disabling analytics")
    getstatusoutput("touch ~/.config/alibuild/disable-analytics")
    return False
  return True 
Example #30
Source File: StarTracker_5_deg_FITS.py    From Star_Tracker with GNU General Public License v3.0 5 votes vote down vote up
def call_match(ra_dec):
    RA1, DEC1 = ra_dec
    # Transform RA and DEC in string and make the path for catalog.
    path_catalog2 = str(RA1) + '_DEC_' + str(DEC1)
    path_catalog3 = path_catalog1 + path_catalog2
    # Do Match.
    Match1 = 'match ' + path_stars + ' 0 1 2 ' + path_catalog3 + ' 0 1 2 ' + parametros1
    status1, resultado1 = commands.getstatusoutput(Match1)
    return status1, resultado1

# Create the list of parameters.