Exemple #1
0
    def test_should_not_pop_stash_on_failure(self):
        from sh import echo

        git_touch_add_commit('foo', 'bar', 'moo')
        foo_commit, _ = git_log_oneline()[2]

        echo('bar', _out='bar')
        echo('moo', _out='moo')
        git('add', 'bar')

        expected = {
            'bar': 'M ',
            'moo': ' M'
        }
        self.assertEqual(expected, git_status())

        with self.assertRaises(GitRebaseFailed):
            fix(foo_commit)

        status = {
            'bar': 'DU'
        }
        self.assertEqual(status, git_status())

        self.assertEqual(1, git_stash_len())

        actual = git_show('HEAD')['subject']
        expected = git_show(foo_commit)['subject']
        self.assertEqual(expected, actual)
Exemple #2
0
def test():
    if not os.path.isfile('a.out'):
        sh.echo('No executable found', _out='results.txt')
        return
    
    result = sh.Command('./a.out')
    result(_out='results.txt')
 def setUp(self, set_pincode_by_id):
     sh.echo("1234, 1234", _out="/run/shm/cellular.tmp")
     try:
         os.unlink(dirpath + "/../data/cellular.json")
     except Exception:
         pass
     set_pincode_by_id.return_value = True
     self.cellular = Cellular(connection=Mockup())
 def setUp(self, set_pincode_by_id):
     sh.echo("1234, 1234", _out="/run/shm/cellular.tmp")
     try:
         os.unlink(dirpath + "/../data/cellular.json")
     except Exception:
         pass
     set_pincode_by_id.return_value = True
     self.cellular = Cellular(connection=Mockup())
Exemple #5
0
def echo_hello_world_cmd(**kwargs):
    """
    Usage:
        echo hello world --user <user> <target> [--chinese (yes|no)]

    Options:
        --user <user>             Hello World [default: root]
        -c,--chinese              Use Chinese to say hello world
    """
    print echo("echo hello world:" + kwargs["user"])
Exemple #6
0
    def test_should_rollback_on_failure_if_requested(self):
        from sh import echo

        git_touch_add_commit('foo', 'bar')
        foo_commit, _ = git_log_oneline()[1]
        echo('bar', _out='bar')
        git('add', 'bar')

        with self.assertRaises(GitRebaseFailed):
            with git_state_invariant():
                fix('--atomic', foo_commit)
Exemple #7
0
 def _collect_block(self, sysinfo_path):
     try:
         block = Path("/sys/block")
         results = open(Path(sysinfo_path, "block_params.log"), "a+")
         if block.exists():
             for f in block.rglob("[s,h,v]d*/*"):
                 if f.is_file():
                     sh.echo(f, _out=results)
                     sh.cat(f, _out=results)
     except Exception:
         pass
Exemple #8
0
    def test_unicode_arg(self):
        from sh import echo
        if IS_PY3: test = "漢字"
        else: test = "漢字".decode("utf8")
        p = echo(test).strip()

        self.assertEqual(test, p)
 def convert(match):
     source = match.groups()[0]
     source = '\n'.join(l.strip() for l in source.split('\n'))
     source = "<pre>%s</pre>" % source
     rst_source = pandoc(echo(source), f='html', t='rst').stdout.decode('utf8')
     # rst_source = rst_source.strip().replace('\n', '\n   ') + '\n'
     return rst_source
Exemple #10
0
    def test_stringio_output(self):
        from sh import echo
        if IS_PY3:
            from io import StringIO
            from io import BytesIO as cStringIO
        else:
            from StringIO import StringIO
            from cStringIO import StringIO as cStringIO

        out = StringIO()
        echo("-n", "testing 123", _out=out)
        self.assertEqual(out.getvalue(), "testing 123")

        out = cStringIO()
        echo("-n", "testing 123", _out=out)
        self.assertEqual(out.getvalue().decode(), "testing 123")
 def convert(match):
     source = match.groups()[0]
     source = '\n'.join(l.strip() for l in source.split('\n'))
     source = "<pre>%s</pre>" % source
     rst_source = pandoc(echo(source), f='html', t='rst').stdout.decode('utf8')
     # rst_source = rst_source.strip().replace('\n', '\n   ') + '\n'
     return rst_source
def avi_seek(seek):
  fifo = '/tmp/omxplayer_fifo'

  direction = ''
  if seek == 1:
    direction = "$'\x1b\x5b\x42'"
  elif seek == 2:
    direction = "$'\x1b\x5b\x44'"
  elif seek == 3:
    direction = "$'\x1b\x5b\x43'"
  elif seek == 4:
    direction = "$'\x1b\x5b\x41'"
  else:
    direction = "."

  sh.echo('-n', direction, '>', fifo, _bg=True)
Exemple #13
0
 def _share(self, item):
     collection_ids = [self.collection_id()]
     item_id = item["id"]
     result = bw.share(
         item_id, self.org_id(), bw.encode(echo(json.dumps(collection_ids)))
     )
     return json.loads(str(result.stdout, "utf-8").rstrip())
Exemple #14
0
    def test_stringio_output(self):
        from sh import echo
        if IS_PY3:
            from io import StringIO
            from io import BytesIO as cStringIO
        else:
            from StringIO import StringIO
            from cStringIO import StringIO as cStringIO

        out = StringIO()
        echo("-n", "testing 123", _out=out)
        self.assertEqual(out.getvalue(), "testing 123")

        out = cStringIO()
        echo("-n", "testing 123", _out=out)
        self.assertEqual(out.getvalue().decode(), "testing 123")
Exemple #15
0
def host_connect(request, board):
    """
    Return board and host pins that are wired together
    """
    # FIXME: Make it possible to overrride these
    pin = 'D5'
    gpionr = 17

    gpio = None

    sh.sudo.tee(sh.echo(gpionr), '/sys/class/gpio/export')
    time.sleep(0.5)

    def teardown():
        if gpio:
            gpio.close()
        sh.sudo.tee(sh.echo(gpionr), '/sys/class/gpio/unexport')

    request.addfinalizer(teardown)

    gpio = periphery.GPIO(gpionr)
    gpio.direction = 'in'

    if check_host_connect(board, gpio, pin):
        return gpio, pin
    else:
        return None
Exemple #16
0
    def test_unicode_arg(self):
        from sh import echo
        if IS_PY3: test = "漢字"
        else: test = "漢字".decode("utf8")
        p = echo(test).strip()

        self.assertEqual(test, p)
Exemple #17
0
    def test_search(self):
        """Make sure aspiration search is the same as ordinary search
        Uses random fens as values, so not guaranteed to produce the same
        output when run multiple times"""
        lines = str(sh.rl("test/data/fenio.fens", "--count=10")).rstrip("\n")

        sh.make("aspire_search")
        run = sh.Command("./aspire_search")
        aspire_output = str(run(sh.echo(lines)))

        sh.make("no_aspire_search")
        run = sh.Command("./no_aspire_search")
        no_aspire_output = str(run(sh.echo(lines)))

        for fen_orig, fen1, fen2 in zip(lines.split("\n"), aspire_output.split("\n"), no_aspire_output.split("\n")):
            self.assertEquals(fen1, fen2, "Original fen: '%s'" % fen_orig)
def dmenu(choices: Optional[Iterable] = None) -> str:
    if choices:
        dmenu_choices = "\n".join(choices)
        return_value = sh.dmenu(sh.echo(dmenu_choices))
    else:
        return_value = sh.dmenu()
    choice = return_value.stdout.decode().strip()
    return choice
Exemple #19
0
    def test_unicode_arg(self):
        from sh import echo

        test = "漢字"
        if not IS_PY3: test = test.decode("utf8")

        p = echo(test).strip()
        self.assertEqual(test, p)
Exemple #20
0
 def test_unicode_arg(self):
     from sh import echo
     
     test = "漢字"
     if not IS_PY3: test = test.decode("utf8")
     
     p = echo(test).strip()
     self.assertEqual(test, p)
Exemple #21
0
    def say(self, message, voice=None, block=True):
        if not voice:
            voice = self.default_voice

        voice_part = '(voice_{0})'.format(voice)
        text_part = '(SayText "{0}")'.format(common.sterilize(message))
        command = voice_part + text_part
        festival(echo(command), _bg=not block)
Exemple #22
0
    def test_search(self):
        """Make sure aspiration search is the same as ordinary search
        Uses random fens as values, so not guaranteed to produce the same
        output when run multiple times"""
        lines = random.sample(open("test/data/fenio.fens").readlines(), 10)

        sh.make("aspire_search")
        run = sh.Command("./aspire_search")
        aspire_output = str(run(sh.echo(lines)))

        sh.make("no_aspire_search")
        run = sh.Command("./no_aspire_search")
        no_aspire_output = str(run(sh.echo(lines)))

        for fen_orig, fen1, fen2 in zip(lines.split('\n'),
                                        aspire_output.split('\n'),
                                        no_aspire_output.split('\n')):
            self.assertEquals(fen1, fen2, "Original fen: '%s'" % fen_orig)
Exemple #23
0
 def do_GET(self):
     self._set_headers()
     myQuery = urlparse(self.path).query
     url = '{0}?{1}'.format(foreman_url,
                            myQuery) if myQuery != '' else foreman_url
     yaml = str(urllib2.urlopen(url).read())
     print(yaml)
     ignition = str(ct(echo(yaml, _piped=True)))
     self.wfile.write(ignition)
Exemple #24
0
def run_jbofihe(args, lojban):
    """ In order to pipe correctly we have to use two commandline wrappers. """
    try:
        return sh.jbofihe(sh.echo(lojban), *args.split())
    except Exception, e:
        print "Got an error: %s" % type(e)
        print "It reads:"
        print e.message
        print "The Exception vanishes in a puff of lojic."
        sys.exit()
Exemple #25
0
    def test_unicode_arg(self):
        from sh import echo

        test = "漢字"
        if not IS_PY3:
            test = test.decode("utf8")

        p = echo(test, _encoding="utf8")
        output = p.strip()
        self.assertEqual(test, output)
Exemple #26
0
def say_sync(text):
    to_say = echo(text)
    audio = festival_client(to_say, ttw=True)
    paplay( audio,
            channels=1,
            raw=True,
            format="s16le",
            rate=32000,
            device="teesink",
    )
Exemple #27
0
def show(text, delay):
    osd_cat = sh.osd_cat.bake(lines=lines,
                              color=color,
                              outline=outline,
                              outlinecolour=outline_color,
                              shadow=shadow,
                              delay=delay,
                              wait=False,
                              font=font)
    osd_cat(sh.echo(text))
Exemple #28
0
    def test_unicode_arg(self):
        from sh import echo

        test = "漢字"
        if not IS_PY3:
            test = test.decode("utf8")

        p = echo(test, _encoding="utf8")
        output = p.strip()
        self.assertEqual(test, output)
Exemple #29
0
 def convert_pronunciation(self, pron: str) -> Tuple[str, float]:
     """
     Returns the pronunciation using phonemes in the output inventory that best
     corresponds to the given pronunciation. 
     """
     if pron == NULL_PRON:
         return NULL_PRON
     formatted = " ".join([f'"{phon}"' for phon in pron.split(" ")])
     result = carmel(sh.echo(formatted), "-silkOQW", 1, self.map_path).strip()
     return result      
Exemple #30
0
    def __init__(self, path, library=None):
        """Pass file path to get the state. Globs are acceptable.
        path - IN  file path or shell glob to pass to eeadm file state <path>
        library - IN If multi-Library system required
        """

        args = ["eeadm", "recall"]
        if library:
            args += ["-l", library]

        logger.debug(f"For file {path} using library {library}")
        sh.eeadm(sh.echo(path), "recall", _bg=True)
Exemple #31
0
    def create_loop(self, loop, path, size):
        """Create a new loopback device."""
        is_in = self.find_loop(loop)
        if is_in:
            raise Exception("loop device already installed: %s / %s" % is_in)

        self.ssh.dd("if=/dev/zero", "of=%s" % path, "bs=1M", "count=%d" % size)
        self.ssh.fdisk(sh.echo("-e", r"o\nn\np\n1\n\n\nw"), path)
        self.ssh.losetup(loop, path)

        is_in = self.find_loop(loop)
        if not is_in:
            raise Exception("fail to create loop device: %s / %s" % is_in)
Exemple #32
0
    def create_loop(self, loop, path, size):
        """Create a new loopback device."""
        is_in = self.find_loop(loop)
        if is_in:
            raise Exception('loop device already installed: %s / %s' % is_in)

        self.ssh.dd('if=/dev/zero', 'of=%s' % path, 'bs=1M', 'count=%d' % size)
        self.ssh.fdisk(sh.echo('-e', r'o\nn\np\n1\n\n\nw'), path)
        self.ssh.losetup(loop, path)

        is_in = self.find_loop(loop)
        if not is_in:
            raise Exception('fail to create loop device: %s / %s' % is_in)
Exemple #33
0
def create_base(folder):
    """
    Create multisite Plone hosting infrastructure on a server..

    Host sites at /srv/plone or chosen cache_folder

    Each folder has a file called buildout.cfg which is the production buildout file
    for this site. This might not be a real file, but a symlink to a version controlled
    file under /srv/plone/xxx/src/yoursitecustomization.policy/production.cfg.

    Log rotate is performed using a global UNIX log rotate script:
    http://opensourcehacker.com/2012/08/30/autodiscovering-log-files-for-logrotate/

    :param folder: Base installation folder for all the sites e.g. /srv/plone
    """
    from sh import apt_get

    with sudo:

        # Return software we are going to need in any case
        # Assumes Ubuntu / Debian
        # More info: https://github.com/miohtama/ztanesh
        if (not which("zsh")) or (not which("git")) or (not which("gcc")):
            # Which returs zero on success
            print "Installing OS packages"
            apt_get("update")
            apt_get("install", "-y", *PACKAGES)

        # Create base folder
        if not os.path.exists(folder):
            print "Creating installation base %s" % folder
            install(folder, "-d")

        # Create nightly restart cron job
        if os.path.exists("/etc/cron.d"):
            print "(Re)setting all sites nightly restart cron job"
            echo(CRON_TEMPLATE, _out=CRON_JOB)

    create_python_env(folder)
Exemple #34
0
    def test_pipe_input(self):
        # NOTE: There is no use in testing this with _tty_in=True, because if you pipe something into a command
        # there never is a TTY connected to stdin (per definition).
        output = gitlint(echo(u"WIP: Pïpe test."),
                         _tty_in=False,
                         _err_to_out=True,
                         _ok_code=[3])

        expected = u"1: T3 Title has trailing punctuation (.): \"WIP: Pïpe test.\"\n" + \
                   u"1: T5 Title contains the word 'WIP' (case-insensitive): \"WIP: Pïpe test.\"\n" + \
                   u"3: B6 Body message is missing\n"

        self.assertEqual(output, expected)
def to_be_terminated():
    # This function determines if termination needs to be addressed.
    if not Path("/clean-exit-attempted").is_file():
        try:
            resp = requests.get(
                'http://169.254.169.254/latest/meta-data/spot/termination-time'
            )
            resp.raise_for_status()
            wall(echo('Restarting job as this instance will be terminated.'))
            return True
        except:
            return False
    else:
        return False
Exemple #36
0
 def test_stdin_pipe(self):
     """ Test piping input into gitlint.
         This is the equivalent of doing:
         $ echo "foo" | gitlint
     """
     # NOTE: There is no use in testing this with _tty_in=True, because if you pipe something into a command
     # there never is a TTY connected to stdin (per definition). We're setting _tty_in=False here to be explicit
     # but note that this is always true when piping something into a command.
     output = gitlint(echo(u"WIP: Pïpe test."),
                      _tty_in=False,
                      _err_to_out=True,
                      _ok_code=[3])
     self.assertEqualStdout(
         output, self.get_expected("test_stdin/test_stdin_pipe_1"))
Exemple #37
0
def create_python_env(folder):
    """
    Compile a Python environment with various Python versions to run Plone.

    Create Python's under /srv/plone/python

    Use https://github.com/collective/buildout.python
    """
    from sh import git

    python_target = os.path.join(folder, "python")

    print "Setting up various Python versions at %s" % python_target

    with sudo:

        if not os.path.exists(python_target):
            cd(folder)
            git("clone", "git://github.com/collective/buildout.python.git", "python")

        if not os.path.exists(os.path.join(python_target, "python-2.7", "bin", "python")):
            cd(python_target)
            echo(PYTHON_BUILDOUT, _out="%s/buildout.cfg" % python_target)
            python("bootstrap.py")
            run = Command("%s/bin/buildout" % python_target)
            run()

        pip = Command("%s/python-2.7/bin/pip" % python_target)

        # Avoid buildout bootstrap global python write bug using Distribute 0.6.27
        pip("install", "--upgrade", "Distribute")

        # Plone 4.x sites heavily rely on lxml
        # Create a shared lxml installation. System deps should have been installed before.
        # for plone 3.x do this by hand
        # collective.buildout.python does not do lxml, which is crucial
        pip("install", "lxml")
Exemple #38
0
    def test_stdin_pipe(self):
        """ Test piping input into gitlint.
            This is the equivalent of doing:
            $ echo "foo" | gitlint
        """
        # NOTE: There is no use in testing this with _tty_in=True, because if you pipe something into a command
        # there never is a TTY connected to stdin (per definition). We're setting _tty_in=False here to be explicit
        # but note that this is always true when piping something into a command.
        output = gitlint(echo(u"WIP: Pïpe test."), _tty_in=False, _err_to_out=True, _ok_code=[3])

        expected = u"1: T3 Title has trailing punctuation (.): \"WIP: Pïpe test.\"\n" + \
                   u"1: T5 Title contains the word 'WIP' (case-insensitive): \"WIP: Pïpe test.\"\n" + \
                   u"3: B6 Body message is missing\n"

        self.assertEqual(output, expected)
    def set_hostname(self, hostname):
        """Update hostname

            Args:
                hostname (str): hostname to be updated
        """
        try:
            old_hostname = self.get_hostname()

            is_valid_hostname(hostname)

            sh.hostname("-b", hostname)
            sh.echo(hostname, _out="/etc/hostname")

            try:
                # sed -i 's/ old$/ new/g' /etc/hosts
                sh.sed("-i", "s/ {}$/ {}/g".format(old_hostname, hostname),
                       "/etc/hosts")
            except:
                with open("/etc/hosts", "a") as f:
                    f.write("127.0.0.1       localhost {}\n".format(hostname))
            self.update(id=1, newObj={"hostname": hostname})
        except Exception as e:
            raise e
Exemple #40
0
def create_site_initd_script(name, folder, username):
    """
    Install /etc/init.d boot script for a Plone site.

    We do this Ubuntu style, not sure if works 100% on Debian.

    http://wiki.debian.org/LSBInitScripts

    http://developer.plone.org/hosting/restarts.html#lsbinitscripts-starting-with-debian-6-0
    """

    from sh import chmod

    updaterc = Command("/usr/sbin/update-rc.d")

    script_body = DEBIAN_BOOT_TEMPLATE % dict(user=username, folder=folder, name=name)

    initd_script = "/etc/init.d/%s" % name

    print "Creating start/stop script %s" % initd_script
    with sudo:
        echo(script_body, _out=initd_script)
        chmod("u+x", initd_script)
        updaterc(name, "defaults")
Exemple #41
0
    def create_loop(self, loop, path, size):
        """Create a new loopback device."""
        is_in = self.find_loop(loop)
        if is_in:
            raise Exception('loop device already installed: %s / %s' %
                            is_in)

        self.ssh.dd('if=/dev/zero', 'of=%s' % path, 'bs=1M',
                    'count=%d' % size)
        self.ssh.fdisk(sh.echo('-e', r'o\nn\np\n1\n\n\nw'), path)
        self.ssh.losetup(loop, path)

        is_in = self.find_loop(loop)
        if not is_in:
            raise Exception('fail to create loop device: %s / %s' %
                            is_in)
Exemple #42
0
    def test_pipe_input(self):
        error_msg = None
        # For some odd reason, sh doesn't return the error output when piping something into gitlint.
        # Note that this does work as expected in the test_errors testcase.
        # To work around this we raise and catch an exception
        try:
            gitlint(echo("WIP: Pipe test."), _tty_in=False)
        except ErrorReturnCode as e:
            # StdErr is returned as bytes -> decode to unicode string
            # http://stackoverflow.com/questions/606191/convert-bytes-to-a-python-string
            error_msg = e.stderr.decode("utf-8")

        expected = "1: T3 Title has trailing punctuation (.): \"WIP: Pipe test.\"\n" + \
                   "1: T5 Title contains the word 'WIP' (case-insensitive): \"WIP: Pipe test.\"\n" + \
                   "3: B6 Body message is missing\n"

        self.assertEqual(error_msg, expected)
Exemple #43
0
    def test_pipe_input(self):
        error_msg = None
        # For some odd reason, sh doesn't return the error output when piping something into gitlint.
        # Note that this does work as expected in the test_errors testcase.
        # To work around this we raise and catch an exception
        try:
            gitlint(echo(u"WIP: Pïpe test."), _tty_in=False)
        except ErrorReturnCode as e:
            # StdErr is returned as bytes -> decode to unicode string
            # http://stackoverflow.com/questions/606191/convert-bytes-to-a-python-string
            error_msg = e.stderr.decode(DEFAULT_ENCODING)

        expected = u"1: T3 Title has trailing punctuation (.): \"WIP: Pïpe test.\"\n" + \
                   u"1: T5 Title contains the word 'WIP' (case-insensitive): \"WIP: Pïpe test.\"\n" + \
                   "3: B6 Body message is missing\n"

        self.assertEqual(error_msg, expected)
Exemple #44
0
    def resize(cls, container_id, new_size=10240):
        """resize container disk space, only support devicemapper storage backend

        args:
            new_size: 1024Mb
        """
        dev_path = glob.glob("/dev/mapper/docker-*-*-%s*" % container_id)
        if dev_path:
            dev = os.path.basename(dev_path[0])
        else:
            return

        #load
        table = sh.dmsetup('table', dev).split()
        table[1] = str(int(new_size) * 1024 * 1024 / 512)
        sh.dmsetup((sh.echo(' '.join(table))), 'load', dev)
        sh.dmsetup('resume', dev)
        sh.resize2fs(dev_path[0])
Exemple #45
0
    def resize(cls, container_id, new_size=10240):
        """resize container disk space, only support devicemapper storage backend

        args:
            new_size: 1024Mb
        """
        dev_path = glob.glob("/dev/mapper/docker-*-*-%s*" % container_id)
        if dev_path:
            dev = os.path.basename(dev_path[0])
        else:
            return

        #load
        table = sh.dmsetup('table', dev).split()
        table[1] = str(int(new_size)*1024*1024/512)
        sh.dmsetup((sh.echo(' '.join(table))), 'load', dev)
        sh.dmsetup('resume', dev)
        sh.resize2fs(dev_path[0])
Exemple #46
0
    def test_stdin_pipe_empty(self):
        """ Test the scenario where no TTY is attached an nothing is piped into gitlint. This occurs in
            CI runners like Jenkins and Gitlab, see https://github.com/jorisroovers/gitlint/issues/42 for details.
            This is the equivalent of doing:
            $ echo -n "" | gitlint
        """
        commit_msg = u"WIP: This ïs a title.\nContent on the sëcond line"
        self._create_simple_commit(commit_msg)

        # We need to set _err_to_out explicitly for sh to merge stdout and stderr output in case there's
        # no TTY attached to STDIN
        # http://amoffat.github.io/sh/sections/special_arguments.html?highlight=_tty_in#err-to-out
        output = gitlint(echo("-n", ""),
                         _cwd=self.tmp_git_repo,
                         _tty_in=False,
                         _err_to_out=True,
                         _ok_code=[3])

        self.assertEqual(
            ustr(output),
            self.get_expected("test_stdin/test_stdin_pipe_empty_1"))
Exemple #47
0
    def query(self, cmd):
        expr = cmd[1:].strip()
        if not expr:
            return []

        # math (with octave)
        try:
            expr = "format long;" + expr
            res = sh.octave("--eval", expr) \
                    .strip().replace("ans = ", "")
            if res:
                return [f"{cmd} = {res}"]
        except sh.ErrorReturnCode:
            pass

        # math (with bc)
        try:
            os.environ["BC_LINE_LENGTH"] = "0"
            res = sh.bc(sh.echo(expr), "-l").strip()
            if res:
                return [f"{cmd} = {res}"]
        except sh.ErrorReturnCode:
            pass

        # find. too slow, find an alternative
        # if cmd.startswith("=find "):
        #     cmd = cmd[5:].strip()
        #     if not cmd:
        #         return []
        #     try:
        #         res = sh.locate(cmd).strip()
        #         if res:
        #             files = []
        #             for f in res.split("\n"):
        #                 files.append(f"{cmd} {f}")
        #     except sh.ErrorReturnCode:
        #         pass

        return []
Exemple #48
0
def get_sid(upn, password, domain):
    # Get kerberos ticket using kinit
    sh.kinit(sh.echo(password),(upn))
    logger.info(sh.klist())

    server = ldap3.Server(host=domain, get_info=ldap3.ALL)
    conn = ldap3.Connection(server, user=upn, password=password,
                            auto_bind=True)

    search_base = ','.join(['DC=' + dp for dp in domain.split('.')])
    search_filter = '(&(objectclass=domain))'
    params = {
        'search_base': search_base,
        'search_filter': search_filter,
        'search_scope': ldap3.SUBTREE,
        'attributes': ['objectSid'],
        'paged_size': 1,
        'generator': False
    }

    conn.extend.standard.paged_search(**params)

    return conn.entries[0].objectSid
Exemple #49
0
def imgur():
    savefig("/tmp/pic.png")
    print sh.tee(sh.imgur2("/tmp/pic.png"),"pbcopy")
    print sh.echo("copied to clipboard")
Exemple #50
0
 def test_not_python(self):
     sh.echo('print("Python rocks!")', _out="extra.py")
     sh.coverage('run', 'extra.py')
     sh.echo("<h1>This isn't python!</h1>", _out="extra.py")
     assert self.cover.get_coverage() == []
Exemple #51
0
 def test_missing_file(self):
     sh.echo('print("Python rocks!")', _out="extra.py")
     sh.coverage('run', 'extra.py')
     sh.rm('-f', 'extra.py')
     assert self.cover.get_coverage() == []
Exemple #52
0
 def test_bg_to_int(self):
     from sh import echo
     # bugs with background might cause the following error:
     #   ValueError: invalid literal for int() with base 10: ''
     self.assertEqual(int(echo("123", _bg=True)), 123)
Exemple #53
0
]

if len(storage_slots) == 0:
    print("Failed to get slots.")
    sys.exit(1)

slotmap = {}
for slot in storage_slots:
    (_, _, _, slotnumber, _, _, _, tapeid) = re.split(":|=| +", slot)
    slotmap[tapeid] = slotnumber

for tape in tapes:
    if tape not in slotmap:
        print(f"Could not find tape {tape} in library.")
        sys.exit(1)

# ready to move tapes!

for mailboxnum, tapeid in enumerate(tapes):
    print(
        f"Move tape {tapeid} from slot {slotmap[tapeid]} to mailbox {mailboxnum} ({mailslots[mailboxnum]})."
    )
    print(
        mtx("-f", tape_device, "transfer", slotmap[tapeid],
            mailslots[mailboxnum]))

# update slots

bconsole(echo("-e", "update slots storage=sl150-robot\n\n"))
print("Updated bacula slots.")
    inputs = []
    alu_times = []
    simple_times = []
    alu_command = sh.Command('./alu')
    simple_command = sh.Command('./simple')

    operator = '*'

    for _ in xrange(5000):
        operand1 = str(random.randint(1, 32768))
        operand2 = str(random.randint(1, 32768))
        inputs.append(' '.join([operator, operand1, operand2]))

    for i in inputs:
        begin_time = time()
        alu_command(echo(i))
        end_time = time()
        alu_times.append(end_time - begin_time)

        begin_time = time()
        simple_command(echo(i))
        end_time = time()
        simple_times.append(end_time - begin_time)

    print 'Multiplication:\n'

    print 'Average execution time(alu method): %s seconds' % (numpy.average(alu_times))
    print 'Standard deviation in execution time(alu method): %s seconds' % (numpy.std(alu_times))
    print 'Minimum execution time(alu method): %s seconds' % (min(alu_times))
    print 'Maximum execution time(alu method): %s seconds\n' % (max(alu_times))
Exemple #55
0
 def test_bg_to_int(self):
     from sh import echo
     # bugs with background might cause the following error:
     #   ValueError: invalid literal for int() with base 10: ''
     self.assertEqual(int(echo("123", _bg=True)), 123)
def avi_toggle_play():
  fifo = '/tmp/omxplayer_fifo'

  sh.echo('-n', 'p', '>', fifo, _bg=True)
Exemple #57
0
 def FileTran(self, tran_type):
     """
     use SFTP method to put or get file to or from the remote clients
     """
     self.ssh_conn()
     warning_log = self.verify_dir_exist(tran_type)
     self.ftp_conn()
     local, remote = self.fileget()
     local, remote = self.send_file_support_shell(local),\
                     self.send_file_support_shell(remote)
     head_log = "transfer file " + self.hostname
     if tran_type in ["putfile", "putline"]:
         try:
             flag = True
             localname = local.split('/')[-1]
             if remote.endswith('/'):
                 remote = remote + localname
             if local.startswith('/'):
                 pass
             else:
                 local = os.getcwd() + '/' + local
             if tran_type == "putfile":
                 self.sftp.put(local, remote)
                 log = '***put file %s to remote %s %s successfully' % (
                                         local, self.hostname, remote)
                 head_log += ' put file: success'
             else:
                 with open(local ,'r') as f:
                     text = f.read().strip()
                 self.ssh.exec_command("echo -e '{0}' >> {1}".format(text, remote))
                 log = '***put lines %s to remote %s %s successfully' % (
                                         local, self.hostname, remote)
                 head_log += ' put lines: success'
             self.success = 1
             self.logging.info(log)
         except:
             flag = False
             log = "***no local file %s" % local
             head_log += ' put file: fail'
             self.fail = 1
             self.logging.error(log)
     elif tran_type in ["getfile", "getline"]:
         try:
             local, remote = remote, local
             flag = True
             remotename = remote.split('/')[-1]
             if local == '.':
                 local = os.getcwd() + '/' + remotename
             if local.endswith('/'):
                 local = local + remotename
             if local.startswith('/'):
                 pass
             else:
                 local = os.getcwd() + '/' + local
             if tran_type == "getfile":
                 self.sftp.get(remote ,local)
                 log = '***get remote file %s %s to local %s successfully' % (
                                             self.hostname, remote, local)
                 head_log += ' get file: success'
             else:
                 stdin,stdout,stderr = self.ssh.exec_command("cat {0}".format(remote))
                 text = stdout.read().strip()
                 sh.echo('-e', text ,_out=local)
                 log = '***get lines %s to remote %s %s successfully' % (
                                                 remote, self.hostname, local)
                 head_log += ' get lines: success'
             self.success = 1
             self.logging.info(log)
         except:
             flag = False
             log = '***' + self.hostname + " has no remote file %s" % remote
             head_log += ' get file: fail'
             self.fail = 1
             self.logging.error(log)
     self.file_log_export(head_log, warning_log, log, flag)
     self.close_all()
Exemple #58
0
log_file.writelines(berry_images)
log_file.close()
print('\033[1;32;40m images written to images.log file')

print('\033[1;32;40m checking gpio for boot selection')
for gpio_pin, image in boot_selector_config.gpio_image.items():
    gpio.setup(gpio_pin, gpio.IN, pull_up_down=gpio.PUD_UP)
    gpio_state = gpio.input(gpio_pin)
    print('\033[1;36;40m \tgpio {0} = {1}'.format(gpio_pin,
                                                  not bool(gpio_state)))
    if not gpio_state:
        #looking for a LOW signal
        try:
            print(
                '\033[1;32;40m writing {0} to /mnt/data/runonce'.format(image))
            sh.echo(image, _out=runonce_file)
            runonce_file.close()
            print('\033[1;33;40m rebooting in:')
            for t in reversed(range(boot_selector_config.countdown)):
                print('\033[1;31;40m \t{0}'.format(t))
                sleep(1)
            gpio.cleanup()
            sh.reboot()
        except Exception as e:
            print('\033[1;31;40m {0}\n{1} -> {2}'.format(
                e,
                type(e).__name__, e.args))
            quit(2)
gpio.cleanup()
runonce_file.close()
print('\033[1;31;40m error: check the switch connections or config')