示例#1
0
文件: ui.py 项目: mattrixman/scOOBE
def has_text(text):
    try:
        egrep(adb.shell(['uiautomator dump /dev/tty']), ".*" + text + ".*")
        return True
    except ErrorReturnCode:
        pass
    return False
示例#2
0
def lemma_to_inflections(lemma: str) -> list:
    line = sh.egrep(f'([^-\']|^){lemma}([^-\']|$)', str(lemma_pathname))
    line = sh.egrep(f'\\b{lemma}\\b', _in=line)
    inflections = line.split()[-1].split(',')
    if lemma not in inflections:
        inflections.insert(0, lemma)
    return inflections
示例#3
0
def extract_shift_contribution(contribution_name,fn):
    if contribution_name in ['core']:
        aa = sh.egrep(contribution_name+' sigma:',fn).split('\n')[:-1]
        ee = [cc*np.eye(3) for cc in map(extract_shift_scalar,aa)]
    elif contribution_name in ['Macroscopic shape']:
        aa = str(sh.egrep('-A 3',contribution_name,fn))
        ee = extract_shift_tensor(aa)
    elif contribution_name in ['bare','para','dia','para_oo','para_lq','Total']:
        aa = sh.grep('-A 3',contribution_name+' sigma:',fn).split('--\n')
        ee = map(extract_shift_tensor,aa)
    return ee
示例#4
0
def word_to_lemma(word: str):
    result = None
    try:
        _ = sh.egrep(f'([^-\']|^){word}([^-\']|$)', str(lemma_pathname))
        result = sh.egrep(f'\\b{word}\\b', _in=_)
    except sh.ErrorReturnCode_1:
        return None
    else:
        if '/' in result:
            lemma = result.split(' ')[0].split('/')[0]
        else:
            lemma = result.split(' ')[0]
        return lemma
示例#5
0
 def get_matching_logs(self):
     logs = []
     try:
         logs = egrep("-i", self.pattern, self.log_file)
     except ErrorReturnCode_1:
         pass
     return logs
示例#6
0
def oxford(keyword: str) -> str:
    try:
        record = sh.egrep(f'\\b{keyword}\\b',
                          str(oxford_pathname)).stdout.decode()
    except sh.ErrorReturnCode_1:
        return ""
    else:
        return record
示例#7
0
def print_device_packages():

    listing = str(grep(egrep(adb(['shell', 'dumpsys', 'package', '*']), r'Package..com\.clover|versionName'), ['Package', '-A1']))
    package_names = re.findall(r'Package \[(.*)\].*', listing)
    versions = list(map(lambda x : x.strip(), re.findall(r'versionName=(.*)', listing)))
    package2version = {}
    for p, v in zip(package_names, versions):
        package2version[p] = v
    print(json.dumps(package2version, indent=4))
示例#8
0
def search_from_directory(directory: Path, keyword: str, suffix: str) -> str:
    combinations = []
    words = keyword.split(' ')
    for word in words:
        lemma = word_to_lemma(word)
        if lemma is None:
            combinations.append((word, ))
        else:
            inflections = lemma_to_inflections(lemma)
            combinations.append(inflections)
    keywords = list(itertools.product(*combinations))

    def words_to_keyword(words):
        return ' '.join(words)

    keywords = [words_to_keyword(words) for words in keywords]
    pattern = '\\b({})\\b'.format('|'.join(keywords))
    record = ''

    for pathname in directory.rglob(f'*.{suffix}'):
        count = None
        running_command = None
        try:
            running_command = sh.egrep('-c', pattern, f'{pathname}')
        except sh.ErrorReturnCode_1:
            pass
        else:
            count = int(running_command)
            record += '<details>'
            record += f'<summary>{pathname.stem} <b>{count}</b></summary>'
            for line in sh.egrep(pattern, f'{pathname}'):
                record += sh.sed('-E', f's/{pattern}/<b>&<\\/b>/g',
                                 _in=line).stdout.decode().strip()
                record += '<br>'
                record += '<br>'
            record += '</details>'
    if record != '':
        record = f"""
        <b>{directory.stem}</b>
        <br>
        """ + record
    return record
示例#9
0
    def start(self):
        try:
            tty.setcbreak(sys.stdin.fileno())
            while True:
                if self.isData():
                    c = sys.stdin.read(1)
                    self.s += c
                    if c == '\x0A': # Return
                        continue;
                    if c == '\x7f': # Backspace
                        self.s = self.s[:-2]

                    if self.s != '':
                        n = Interact()
                        egrep(
                            # Recursive
                            "-R",
                            # Case insensitive
                            "-i",
                            # Prefix line number
                            "-n",
                            # Ignore binary
                            "-I",
                            # Max 3 results per file
                            "-m", 3,
                            # 2 lines of context
                            "-C", 2,
                            # Only list files
                            "-l",
                            self.escape(self.s), self.path, _bg=True, _out=n)
                        if self.old is not None:
                            self.old.mute()
                            print
                            print '-----------------------------------------'
                            print self.s
                        self.old = n
        
        finally:
            termios.tcsetattr(sys.stdin, termios.TCSADRAIN, self.old_settings)
示例#10
0
def compareIp():
    logging.debug("Comparing ip...")
    #ip a s eth0 | egrep -o 'inet [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}' | cut -d' ' -f2
    curIp = str(cut(egrep(ip('a', 's', 'eth0'), '-o', 'inet [0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}'), '-d', ' ', '-f2')).strip()
    masterNetworkCfg = cat('/etc/systemd/network/000-master.network').split('\n')
    for i in range(len(masterNetworkCfg)):
        if masterNetworkCfg[i] == '[Address]':
            masterIp = masterNetworkCfg[i+1].split('=')[1].strip()
            logging.debug("Master ip found, breaking the loop...")
            break 
    if curIp==masterIp:
        logging.debug("Master IP == cur IP...")
        return True, masterIp
    logging.debug("Master IP != cur IP...")
    return False, masterIp
示例#11
0
    def _dockerHost(self, config):
        """
        Function to check if container/external IP have connections
        open to our main container. This container is running in
        "network=host" like "hass" and "mosquitto".
        """

        # Check configuration
        for conf in [CONF_NAME, CONF_HOST, CONF_PORT, CONF_CLIENTS]:
            if conf not in config:
                LOGGER.error(
                    "%s: Invalid config, missing '%s' in config=%s",
                    ATTR_DOCKERHOST,
                    conf,
                    str(config),
                )
                return

        if not config[CONF_ENABLED]:
            LOGGER.debug("%s: %s is not enabled", ATTR_DOCKERHOST,
                         config[CONF_NAME])
            return

        # Just report it in debug mode
        LOGGER.debug("%s: %s is enabled", ATTR_DOCKERHOST, config[CONF_NAME])
        LOGGER.debug("%s: config=%s", ATTR_DOCKERHOST, str(config))

        # Get our docker client
        client = docker.from_env()

        # Check if main docker container exist and is running
        try:
            container = client.containers.get(config[CONF_CONTAINER])
        except docker.errors.NotFound:
            # Container doesn't exit, so we shouldn't continue
            LOGGER.error(
                "%s: %s primary container %s does not exist",
                ATTR_DOCKERHOST,
                config[CONF_NAME],
                config[CONF_CONTAINER],
            )
            # Add to error list
            msg = "Container {} does not exist".format(config[CONF_CONTAINER])
            self._handleMsg(
                ATTR_ALARM,
                ATTR_DOCKERHOST,
                ATTR_CONTAINERS,
                config[CONF_NAME],
                config[CONF_CONTAINER],
                msg,
            )
            return

        # The container needs to be running, otherwise no connectivity can be there
        if container.status != "running":
            LOGGER.error(
                "%s: %s primary container %s not running",
                ATTR_DOCKERHOST,
                config[CONF_NAME],
                config[CONF_CONTAINER],
            )
            # Add to error list
            msg = "Container {} not running".format(config[CONF_CONTAINER])
            self._handleMsg(
                ATTR_ALARM,
                ATTR_DOCKERHOST,
                ATTR_CONTAINERS,
                config[CONF_NAME],
                config[CONF_CONTAINER],
                msg,
            )
            return

        pid = container.attrs["State"]["Pid"]
        LOGGER.debug(
            "%s: %s is running with pid=%d",
            ATTR_DOCKERHOST,
            config[CONF_CONTAINER],
            pid,
        )

        # Clear possible error with primary container
        msg = "Container {} alarm cleared".format(config[CONF_CONTAINER])
        self._handleMsg(
            ATTR_CLEAR,
            ATTR_DOCKERHOST,
            ATTR_CONTAINERS,
            config[CONF_NAME],
            config[CONF_CONTAINER],
            msg,
        )

        # Configure errorfound to False
        errorfound = False

        # Go through list of containers connected to primary
        if CONF_CONTAINERS in config[CONF_CLIENTS]:

            host = config[CONF_HOST]
            if self.isIPValid(config[CONF_HOST]):
                host = config[CONF_HOST].replace(".", "\.")

            # We support multiple port(s)
            checklist = []
            if type(config[CONF_PORT]).__name__ == "list":
                for port in config[CONF_PORT]:
                    checklist.append((".*:.*\s*" + host + ":" + str(port) +
                                      "\s*ESTABLISHED$"))
            else:
                checklist.append((".*:.*\s*" + host + ":" +
                                  str(config[CONF_PORT]) + "\s*ESTABLISHED$"))

            checkfor = "|".join(checklist)

            LOGGER.debug("%s: Connection string '%s'", ATTR_DOCKERHOST,
                         checkfor)

            for name in config[CONF_CLIENTS][CONF_CONTAINERS]:

                # Check if client container exist and is running
                try:
                    container = client.containers.get(name)
                except docker.errors.NotFound:
                    # Container doesn't exit, so we shouldn't continue
                    LOGGER.error(
                        "%s: %s client container %s does not exist",
                        ATTR_DOCKERHOST,
                        config[CONF_NAME],
                        name,
                    )
                    # Add to error list
                    msg = "Container {} does not exist".format(name)
                    self._handleMsg(
                        ATTR_ALARM,
                        ATTR_DOCKERHOST,
                        ATTR_CONTAINERS,
                        config[CONF_NAME],
                        name,
                        msg,
                    )
                    errorfound = True
                    continue

                # The container needs to be running, otherwise no connectivity can be there
                if container.status != "running":
                    LOGGER.error(
                        "%s: %s client container %s not running",
                        ATTR_DOCKERHOST,
                        config[CONF_NAME],
                        name,
                    )
                    # Add to error list
                    msg = "Container {} not running".format(name)
                    self._handleMsg(
                        ATTR_ALARM,
                        ATTR_DOCKERHOST,
                        ATTR_CONTAINERS,
                        config[CONF_NAME],
                        name,
                        msg,
                    )
                    errorfound = True
                    continue

                pid = container.attrs["State"]["Pid"]
                LOGGER.debug("%s: %s is running with pid=%d", ATTR_DOCKERHOST,
                             name, pid)

                # Check if we have connectivity, we go in their namespace
                # With docker this is *only* possible through namespace and shell,
                # there doesn't seem to be a simple python option
                with Namespace(pid, "net"):
                    try:
                        netstatparam = "-a" if config[CONF_DNS] else "-na"
                        outp = sh.egrep(
                            sh.netstat(netstatparam, _tty_out=False), checkfor)
                    except sh.ErrorReturnCode_1:
                        # Not found, so no connection
                        LOGGER.error(
                            "%s: container %s not connected %s",
                            ATTR_DOCKERHOST,
                            name,
                            config[CONF_NAME],
                        )

                        msg = "Container {} not connected to {}".format(
                            config[CONF_CONTAINER], config[CONF_NAME])
                        self._handleMsg(
                            ATTR_ALARM,
                            ATTR_DOCKERHOST,
                            ATTR_CONTAINERS,
                            config[CONF_NAME],
                            name,
                            msg,
                        )
                        errorfound = True
                        continue

                    except sh.ErrorReturnCode as e:
                        # Not good, shouldn't happen
                        LOGGER.error(
                            "%s: container %s returned an error with checkfor='%s'. msg='%s'",
                            ATTR_DOCKERHOST,
                            name,
                            checkfor,
                            str(e),
                        )

                        msg = "Container {} not connected to {} (RC>1)".format(
                            config[CONF_CONTAINER], config[CONF_NAME])
                        self._handleMsg(
                            ATTR_ALARM,
                            ATTR_DOCKERHOST,
                            ATTR_CONTAINERS,
                            config[CONF_NAME],
                            name,
                            msg,
                        )
                        errorfound = True
                        continue

                    # RC=0, should be good
                    #if outp.count("\n") > 1:
                    #    LOGGER.error(
                    #        "%s: container %s returned more then 1 line '%s'",
                    #        ATTR_DOCKERHOST,
                    #        name,
                    #        outp,
                    #    )

                    LOGGER.debug(
                        "%s: container %s connected to %s",
                        ATTR_DOCKERHOST,
                        name,
                        config[CONF_NAME],
                    )

                # Clear possible error with primary container
                msg = "Container {} alarm cleared".format(name)
                self._handleMsg(
                    ATTR_CLEAR,
                    ATTR_DOCKERHOST,
                    ATTR_CONTAINERS,
                    config[CONF_NAME],
                    name,
                    msg,
                )

        # Check the hosts (external IPs)
        if CONF_HOSTS in config[CONF_CLIENTS]:

            host = config[CONF_HOST]
            if self.isIPValid(config[CONF_HOST]):
                host = config[CONF_HOST].replace(".", "\.")

            # We support multiple port(s)
            checklist = []
            if type(config[CONF_PORT]).__name__ == "list":
                for port in config[CONF_PORT]:
                    checklist.append("\s*" + host + ":" + str(port) +
                                     "\s*{}:.*\s*ESTABLISHED$")
            else:
                checklist.append("\s*" + host + ":" + str(config[CONF_PORT]) +
                                 "\s*{}:.*\s*ESTABLISHED$")

            checkfor = "|".join(checklist)

            checkfor = ("\s*" + host + ":" + str(config[CONF_PORT]) +
                        "\s*{}:.*\s*ESTABLISHED$")

            for name in config[CONF_CLIENTS][CONF_HOSTS]:

                try:
                    netstatparam = "-a" if config[CONF_DNS] else "-na"
                    host = name
                    if self.isIPValid(name):
                        host = name.replace(".", "\.")

                    LOGGER.debug(
                        "%s: Connection string '%s'",
                        ATTR_DOCKERHOST,
                        checkfor.format(host),
                    )
                    outp = sh.egrep(sh.netstat(netstatparam, _tty_out=False),
                                    checkfor.format(host))
                except sh.ErrorReturnCode_1:
                    # Not found, so no connection
                    LOGGER.error(
                        "%s: host %s not connected %s",
                        ATTR_DOCKERHOST,
                        name,
                        config[CONF_NAME],
                    )

                    msg = "Host {} not connected to {}".format(
                        name, config[CONF_NAME])
                    self._handleMsg(
                        ATTR_ALARM,
                        ATTR_DOCKERHOST,
                        ATTR_HOSTS,
                        config[CONF_NAME],
                        name,
                        msg,
                    )
                    errorfound = True
                    continue

                except sh.ErrorReturnCode as e:
                    # Not good, shouldn't happen
                    LOGGER.error(
                        "%s: host %s returned an error with checkfor='%s'. msg='%s'",
                        ATTR_DOCKERHOST,
                        name,
                        checkfor.format(host),
                        str(e),
                    )

                    msg = "Host {} not connected to {} (RC>1)".format(
                        name, config[CONF_NAME])
                    self._handleMsg(
                        ATTR_ALARM,
                        ATTR_DOCKERHOST,
                        ATTR_HOSTS,
                        config[CONF_NAME],
                        name,
                        msg,
                    )
                    errorfound = True
                    continue

                # RC=0, should be good
                if outp.count("\n") > 1:
                    LOGGER.error(
                        "%s: host %s returned more then 1 line '%s'",
                        ATTR_DOCKERHOST,
                        name,
                        outp,
                    )

                LOGGER.debug(
                    "%s: host %s connected to %s",
                    ATTR_DOCKERHOST,
                    name,
                    config[CONF_NAME],
                )

                # Clear possible error with primary container
                msg = "Host {} alarm cleared".format(name)
                self._handleMsg(
                    ATTR_CLEAR,
                    ATTR_DOCKERHOST,
                    ATTR_HOSTS,
                    config[CONF_NAME],
                    name,
                    msg,
                )

        # Configure errorfound to False
        if not errorfound:
            LOGGER.debug("%s: OK", ATTR_DOCKERHOST)
示例#12
0
#!/usr/bin/env python
#
# LaunchBar Action Script
#
import json
import sh
import re

try:
    result = str(
        sh.egrep(sh.ioreg('-r', '-l', '-n', 'AppleHSBluetoothDevice'),
                 r'"BatteryPercent" = |^  \|   "Bluetooth Product Name" = '))
except sh.ErrorReturnCode:
    print('None Bluetooth Connecting.')
    quit()

names = [
    match.group(1) for match in re.finditer(r'Product Name" = "(.+?)"', result)
]
BatteryPercent_nums = [
    match.group(1) for match in re.finditer(r'Percent" = (\d+)', result)
]

name_percent_pairs = [
    name + " : " + bp + "%" for name in names for bp in BatteryPercent_nums
]

items = []
for pair in name_percent_pairs:
    item = {}
    item['title'] = pair
示例#13
0
 def ui_command_check_services(self):
     print sh.egrep(sh.initctl('list'), 'solarsan|targetcli|mongo')