def test_which(self): """ Test the function which """ self.assertRegex(tools.which("ls"), r'/.*/ls') self.assertEqual(tools.which('backintime'), os.path.join(os.getcwd(), 'backintime')) self.assertIsNone(tools.which("notExistedCommand"))
def decode(self, filename, target): """decode a file to wav""" if not os.path.isfile(filename): logger.error("Decoding failed: %s not found" % filename) return False mp3count = 0 oggcount = 0 if (lower(filename[-4:]) == ".mp3"): mp3count = mp3count + 1 if (lower(filename[-4:]) == ".ogg"): oggcount = oggcount + 1 # Check whether mpg123 and oggdec exists mpg123_command = which("mpg123") oggdec_command = which("oggdec") if ((mp3count > 0) and (mpg123_command == "")): logger.warn( "mpg123 not found for converting mp3 files" ) if ((oggcount > 0) and (oggdec_command == "")): logger.warn( "oggdec not found for converting ogg files" ) #logger.info( "Converting %d file(s) now" % (mp3count + oggcount) ) if ((mp3count > 0) or (oggcount > 0)): #if (lower(filename[-4:]) == ".mp3") or (lower(filename[-4:]) == ".ogg"): #wavfilename = "%s/%s.wav" % (targetPath, os.path.basename(filename)[:-4]) #logger.info( "target = " + target ) if (lower(filename[-4:]) == ".mp3"): # Make sure that conversion is done with the correct sample rate file = open(filename, "rb") mpeg3info = mp3info.MP3Info(file) file.close() samplerate = mpeg3info.mpeg.samplerate command = "(%s --stereo -s \"%s\" | sox -t raw -r %d -w -s -c 2 - -r 44100 -t wav \"%s\") 2>&1" % (mpg123_command, escapedfilename(filename), samplerate, escapedfilename(target)) elif (lower(filename[-4:]) == ".ogg"): # get OGG samplerate vf = ogg.vorbis.VorbisFile(filename) vi = vf.info() samplerate = vi.rate channels = vi.channels #logger.info( 'OGG info: samplerate = %s , channels = %s' % (samplerate, channels) ) if ( samplerate != 44100) or (channels != 2): #logger.warn( 'samplerate not 44100, using sox to resample' ) command = "(sox \"%s\" -r 44100 -c 2 -t wav \"%s\") 2>&1" % (escapedfilename(filename), escapedfilename(target)) else: command = "%s -Q -o \"%s\" \"%s\" 2>&1" % (oggdec_command, escapedfilename(target), escapedfilename(filename)) #logger.info( "Executing: %s" % command ) (result, (stdout_output, stderr_output)) = cmdexec(command) if (result != 0): if (lower(filename[-4:]) == ".mp3"): result = listmatch(output, "Playing") output = output[result[0]:] return False else: return True
def test_check_remote_command_fail(self): cmds = [] if tools.checkCommand('nice'): cmds.append('nice') self.cfg.setNiceOnRemote(True) if tools.checkCommand('ionice'): cmds.append('ionice') self.cfg.setIoniceOnRemote(True) if tools.checkCommand('nocache'): cmds.append('nocache') self.cfg.setNocacheOnRemote(True) if tools.checkCommand('screen') and tools.checkCommand('flock'): cmds.extend(('screen', 'flock', 'rmdir', 'mktemp')) self.cfg.setSmartRemoveRunRemoteInBackground(True) # make one after an other command from 'cmds' fail by symlink them # to /bin/false false = tools.which('false') for cmd in cmds: msg = 'current trap: %s' %cmd with self.subTest(cmd = cmd): with TemporaryDirectory() as self.remotePath: self.cfg.setSshSnapshotsPath(self.remotePath) os.symlink(false, os.path.join(self.remotePath, cmd)) self.cfg.setSshPrefix(True, "export PATH=%s:$PATH; " %self.remotePath) ssh = sshtools.SSH(cfg = self.cfg) with self.assertRaisesRegex(MountException, r"Remote host .+ doesn't support '.*?%s.*'" %cmd, msg = msg): ssh.checkRemoteCommands()
def get_lib(self, cursor, uid): """Return the lib wkhtml path""" proxy = self.pool.get('ir.config_parameter') webkit_path = proxy.get_param(cursor, uid, 'webkit_path') if not webkit_path: try: defpath = os.environ.get('PATH', os.defpath).split(os.pathsep) if hasattr(sys, 'frozen'): defpath.append(os.getcwd()) if tools.config['root_path']: defpath.append(os.path.dirname(tools.config['root_path'])) webkit_path = tools.which('wkhtmltopdf', path=os.pathsep.join(defpath)) except IOError: webkit_path = None if webkit_path: return webkit_path raise except_osv( _('Wkhtmltopdf library path is not set'), _('Please install executable on your system' \ ' (sudo apt-get install wkhtmltopdf) or download it from here:' \ ' http://code.google.com/p/wkhtmltopdf/downloads/list and set the' \ ' path in the ir.config_parameter with the webkit_path key.' \ 'Minimal version is 0.9.9') )
def startSshAgent(self): """ Start a new ``ssh-agent`` if it is not already running. Raises: exceptions.MountException: if starting ``ssh-agent`` failed """ SOCK = "SSH_AUTH_SOCK" PID = "SSH_AGENT_PID" if os.getenv(SOCK, "") and os.getenv(PID, ""): logger.debug("ssh-agent already running. Skip starting a new one.", self) return sshAgent = tools.which("ssh-agent") if not sshAgent: raise MountException("ssh-agent not found. Please make sure it is installed.") sa = subprocess.Popen([sshAgent], stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) out, err = sa.communicate() if sa.returncode: raise MountException("Failed to start ssh-agent: [{}] {}".format(sa.returncode, err)) m = re.match(r"{}=([^;]+);.*{}=(\d+);".format(SOCK, PID), out, re.DOTALL) if m: logger.debug("ssh-agent started successful: {}={} | {}={}".format(SOCK, m.group(1), PID, m.group(2)), self) os.environ[SOCK] = m.group(1) os.environ[PID] = m.group(2) atexit.register(os.kill, int(m.group(2)), signal.SIGKILL) else: raise MountException("No matching output from ssh-agent: {} | {}".format(out, err))
def __init__(self, cfg = None, profile_id = None, tmp_mount = False, parent = None): self.config = cfg if self.config is None: self.config = config.Config() self.profile_id = profile_id if self.profile_id is None: self.profile_id = self.config.get_current_profile() self.tmp_mount = tmp_mount self.parent = parent if self.config.get_password_use_cache(self.profile_id): pw_cache = password.Password_Cache(self.config) action = None running = pw_cache.status() if not running: logger.debug('pw-cache is not running', self) action = 'start' if running and not pw_cache.check_version(): logger.debug('pw-cache is running but is an old version', self) action = 'restart' bit = tools.which('backintime') if not action is None and len(bit): cmd = [bit, 'pw-cache', action] logger.debug('Call command: %s' %' '.join(cmd), self) proc = subprocess.Popen(cmd, stdout = open(os.devnull, 'w'), stderr = open(os.devnull, 'w')) if proc.returncode: logger.error('Failed to %s pw-cache: %s' %(action, proc.returncode), self) pass
def startSshAgent(self): """ Start a new ``ssh-agent`` if it is not already running. Raises: exceptions.MountException: if starting ``ssh-agent`` failed """ SOCK = 'SSH_AUTH_SOCK' PID = 'SSH_AGENT_PID' if os.getenv(SOCK, '') and os.getenv(PID, ''): logger.debug('ssh-agent already running. Skip starting a new one.', self) return sshAgent = tools.which('ssh-agent') if not sshAgent: raise MountException( 'ssh-agent not found. Please make sure it is installed.') if isinstance(sshAgent, str): sshAgent = [ sshAgent, ] sa = subprocess.Popen(sshAgent, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) out, err = sa.communicate() if sa.returncode: raise MountException('Failed to start ssh-agent: [{}] {}'.format( sa.returncode, err)) m = re.match( r'.*{}(?:=|\s)([^;]+);.*{}(?:=|\s)(\d+);'.format(SOCK, PID), out, re.DOTALL | re.MULTILINE) if m: logger.debug( 'ssh-agent started successful: {}={} | {}={}'.format( SOCK, m.group(1), PID, m.group(2)), self) os.environ[SOCK] = m.group(1) os.environ[PID] = m.group(2) atexit.register(os.kill, int(m.group(2)), signal.SIGKILL) else: raise MountException( 'No matching output from ssh-agent: {} | {}'.format(out, err))
def __init__(self, cfg = None, profile_id = None, tmp_mount = False, parent = None): self.config = cfg if self.config is None: self.config = config.Config() self.profile_id = profile_id if self.profile_id is None: self.profile_id = self.config.currentProfile() self.tmp_mount = tmp_mount self.parent = parent if self.config.passwordUseCache(self.profile_id): cache = password.Password_Cache(self.config) action = None running = cache.status() if not running: logger.debug('pw-cache is not running', self) action = 'start' if running and not cache.checkVersion(): logger.debug('pw-cache is running but is an old version', self) action = 'restart' bit = tools.which('backintime') if not action is None and not bit is None and len(bit): cmd = [bit, 'pw-cache', action] logger.debug('Call command: %s' %' '.join(cmd), self) proc = subprocess.Popen(cmd, stdout = subprocess.DEVNULL, stderr = subprocess.DEVNULL) if proc.returncode: logger.error('Failed to %s pw-cache: %s' %(action, proc.returncode), self) pass
def startSshAgent(self): """ Start a new ``ssh-agent`` if it is not already running. Raises: exceptions.MountException: if starting ``ssh-agent`` failed """ SOCK = 'SSH_AUTH_SOCK' PID = 'SSH_AGENT_PID' if os.getenv(SOCK, '') and os.getenv(PID, ''): logger.debug('ssh-agent already running. Skip starting a new one.', self) return sshAgent = tools.which('ssh-agent') if not sshAgent: raise MountException('ssh-agent not found. Please make sure it is installed.') if isinstance(sshAgent, str): sshAgent = [sshAgent, ] sa = subprocess.Popen(sshAgent, stdout = subprocess.PIPE, stderr = subprocess.PIPE, universal_newlines = True) out, err = sa.communicate() if sa.returncode: raise MountException('Failed to start ssh-agent: [{}] {}'.format(sa.returncode, err)) m = re.match(r'.*{}(?:=|\s)([^;]+);.*{}(?:=|\s)(\d+);'.format(SOCK, PID), out, re.DOTALL | re.MULTILINE) if m: logger.debug('ssh-agent started successful: {}={} | {}={}'.format(SOCK, m.group(1), PID, m.group(2)), self) os.environ[SOCK] = m.group(1) os.environ[PID] = m.group(2) atexit.register(os.kill, int(m.group(2)), signal.SIGKILL) else: raise MountException('No matching output from ssh-agent: {} | {}'.format(out, err))
def check_plugin_requirements(plugin_name): """Check the plugin-requirements before enabling a plugin""" tools.debug_output(__name__, 'check_requirements', 'Starting for plugin: ' + plugin_name, 1) ## plugin_kill # if (plugin_name == 'kill'): for i, (a) in enumerate(PLUGIN_KILL_REQUIREMENTS): tools.debug_output(__name__, 'check_plugin_requirements', 'Checking ' + a, 1) if tools.which(PLUGIN_KILL_REQUIREMENTS[i]) is None: tools.debug_output( __name__, 'check_plugin_requirements', 'Error: ' + PLUGIN_KILL_REQUIREMENTS[i] + ' is missing. Plugin plugin_' + plugin_name + ' can not be enabled', 3) return False ## plugin_misc # if (plugin_name == 'misc'): for i, (a) in enumerate(PLUGIN_MISC_REQUIREMENTS): tools.debug_output(__name__, 'check_plugin_requirements', 'Checking ' + a, 1) if tools.which(PLUGIN_MISC_REQUIREMENTS[i]) is None: tools.debug_output( __name__, 'check_plugin_requirements', 'Error: ' + PLUGIN_MISC_REQUIREMENTS[i] + ' is missing. Plugin plugin_' + plugin_name + ' can not be enabled', 3) return False ## plugin_search_local # if (plugin_name == 'search_local'): for i, (a) in enumerate(PLUGIN_SEARCH_LOCAL_REQUIREMENTS): tools.debug_output(__name__, 'check_plugin_requirements', 'Checking ' + a, 1) if tools.which(PLUGIN_SEARCH_LOCAL_REQUIREMENTS[i]) is None: tools.debug_output( __name__, 'check_plugin_requirements', 'Error: ' + PLUGIN_SEARCH_LOCAL_REQUIREMENTS[i] + ' is missing. Plugin plugin_' + plugin_name + ' can not be enabled', 3) return False ## plugin_session # if (plugin_name == 'session'): for i, (a) in enumerate(PLUGIN_SESSION_REQUIREMENTS): tools.debug_output(__name__, 'check_plugin_requirements', 'Checking ' + a, 1) if tools.which(PLUGIN_SESSION_REQUIREMENTS[i]) is None: tools.debug_output( __name__, 'check_plugin_requirements', 'Error: ' + PLUGIN_SESSION_REQUIREMENTS[i] + ' is missing. Plugin plugin_' + plugin_name + ' can not be enabled', 3) return False ## if a plugin has no requirements - everything is fine return True
def test_which(self): """ Test the function which """ self.assertRegex(tools.which("ls"), r'/.*/ls') self.assertIsNone(tools.which("notExistedCommand"))
def __init__(self): """ Initialize the process class. """ self.__ProcessTable_ps_command = tools.which("ps")