sys.stdin.isatty

Here are the examples of the python api sys.stdin.isatty taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

197 Examples 7

Example 1

Project: uncurl
Source File: bin.py
View license
def main():
    if sys.stdin.isatty():
        if len(sys.argv) > 1:
            # If an argument is passed
            result = parse(sys.argv[1])
        else:
            # Otherwise pull from clipboard
            result = parse(xerox.paste())
    else:
        result = parse(sys.stdin.read())
    print(result)

Example 2

Project: prudentia
Source File: io.py
View license
def _hidden_input(msg):
    first_time_input()
    # When using here documents the getpass does not accept automatic inputs
    # so we fall back to the raw input.
    # The raw input will not display the information provided through the heredoc
    if not sys.stdin.isatty():
        return _input(msg)
    else:
        return getpass(msg)

Example 3

Project: pyrocore
Source File: rtevent.py
View license
    def mainloop(self):
        """ The main loop.
        """
        # Print usage if not enough args or bad options
        if len(self.args) < 2:
            self.parser.error("No event type and info hash given!")

        if sys.stdin.isatty():
            self.options.no_fork = True

Example 4

Project: imapbackup
Source File: imapbackup.py
View license
  def spin(self):
    """Rotate the spinner"""
    if sys.stdin.isatty() and not self.nospinner:
      sys.stdout.write("\r" + self.message + " " + self.glyphs[self.pos])
      sys.stdout.flush()
      self.pos = (self.pos+1) % len(self.glyphs)

Example 5

Project: imapbackup
Source File: imapbackup.py
View license
  def stop(self):
    """Erase the spinner from the screen"""
    if sys.stdin.isatty() and not self.nospinner:
      sys.stdout.write("\r" + self.message + "  ")
      sys.stdout.write("\r" + self.message)
      sys.stdout.flush()

Example 6

Project: conary
Source File: epdb_server.py
View license
    def _serve_process(self, slaveFd, serverPid):
        """
            Serves a process by connecting its outputs/inputs to the pty
            slaveFd.  serverPid is the process controlling the master fd
            that passes that output over the socket.
        """
        self.serverPid = serverPid
        if sys.stdin.isatty():
            self.oldTermios = termios.tcgetattr(sys.stdin.fileno())
        else:
            self.oldTermios = None
        self.oldStderr = os.dup(sys.stderr.fileno())
        self.oldStdout = os.dup(sys.stdout.fileno())
        self.oldStdin = os.dup(sys.stdin.fileno())
        os.dup2(slaveFd, 0)
        os.dup2(slaveFd, 1)
        os.dup2(slaveFd, 2)
        os.close(slaveFd)
        self.closed = False

Example 7

Project: conary
Source File: logger.py
View license
    def _controlTerminal(self):
        try:
            # the child should control stdin -- if stdin is a tty
            # that can be controlled
            if sys.stdin.isatty():
                os.tcsetpgrp(0, os.getpgrp())
        except AttributeError:
           # stdin might not even have an isatty method
            pass

Example 8

Project: pyjip
Source File: __init__.py
View license
def read_ids_from_pipe():
    """Read job ids from a stream"""
    import sys
    job_ids = []
    if not sys.stdin.isatty():
        for line in sys.stdin:
            job_ids.append(line.strip().split("\t")[0])
        # reopen stdin
        sys.stdin = open('/dev/tty', 'r')
    return job_ids

Example 9

Project: doge
Source File: core.py
View license
    def setup(self):
        self.height, self.width = self.get_tty_size()
        self.in_is_tty = sys.stdin.isatty()
        self.out_is_tty = sys.stdout.isatty()

        self.pretty = self.out_is_tty
        if sys.platform == 'win32' and os.getenv('TERM') == 'xterm':
            self.pretty = True

Example 10

Project: gup
Source File: cmd.py
View license
def _mark_contents(opts, targets):
	parent_target = _assert_parent_target('--contents')
	if len(targets) == 0:
		assert not sys.stdin.isatty()
		checksum = Checksum.from_stream(sys.stdin.buffer if PY3 else sys.stdin)
	else:
		checksum = Checksum.from_files(targets)
	TargetState(parent_target).add_dependency(checksum)

Example 11

Project: mystic
Source File: tools.py
View license
def getch(str="Press any key to continue"):
    "configurable pause of execution"
    import sys, subprocess
    if sys.stdin.isatty():
       if str is not None:
          print str
       if sys.platform[:3] != 'win':
          raw,cooked = 'stty raw','stty cooked'
       else:
          raw,cooked = '',''
       subprocess.call(raw, shell=True)
       a = sys.stdin.read(1)
       subprocess.call(cooked, shell=True)
       return a
    else:
       if str is not None:
           print str + " and press enter"
       return raw_input()

Example 12

Project: ro-manager
Source File: ro_command.py
View license
def getoptionvalue(val, prompt):
    if not val:
        if sys.stdin.isatty():
            val = raw_input(prompt)
        else:
            val = sys.stdin.readline()
            if val[-1] == '\n': val = val[:-1]
    return val

Example 13

Project: GenSON
Source File: genson.py
View license
def get_stdin():
    """
    Grab stdin, printing simple instructions if it's interactive.
    """
    if sys.stdin.isatty():
        print('Enter a JSON object, then press ctrl-D')
    return sys.stdin

Example 14

Project: python-executor
Source File: tests.py
View license
    def test_tty_option(self):
        """Make sure the ``tty`` option works as expected."""
        # By default we expect the external command to inherit our standard
        # input stream (of course this test suite is expected to work
        # regardless of whether it's connected to a terminal).
        test_stdin_isatty = python_golf('import sys; sys.exit(0 if sys.stdin.isatty() else 1)')
        assert sys.stdin.isatty() == execute(*test_stdin_isatty, check=False)
        # If the command's output is being captured then its standard
        # input stream should be redirected to /dev/null.
        self.assertRaises(ExternalCommandFailed, execute, *test_stdin_isatty, capture=True)
        # If the caller explicitly disabled interactive terminal support then
        # the command's standard input stream should also be redirected to
        # /dev/null.
        self.assertRaises(ExternalCommandFailed, execute, *test_stdin_isatty, tty=False)

Example 15

Project: BitXBay
Source File: electrum_main.py
View license
def prompt_password(prompt, confirm=True):
    import getpass
    if sys.stdin.isatty():
        password = getpass.getpass(prompt)
        if password and confirm:
            password2 = getpass.getpass("Confirm: ")
            if password != password2:
                sys.exit("Error: Passwords do not match.")
    else:
        password = raw_input(prompt)
    if not password:
        password = None
    return password

Example 16

Project: BitXBay
Source File: electrum_main.py
View license
def prompt_password(prompt, confirm=True):
    import getpass
    if sys.stdin.isatty():
        password = getpass.getpass(prompt)
        if password and confirm:
            password2 = getpass.getpass("Confirm: ")
            if password != password2:
                sys.exit("Error: Passwords do not match.")
    else:
        password = raw_input(prompt)
    if not password:
        password = None
    return password

Example 17

Project: twtxt
Source File: helper.py
View license
def validate_text(ctx, param, value):
    conf = click.get_current_context().obj["conf"]
    if isinstance(value, tuple):
        value = " ".join(value)

    if not value and not sys.stdin.isatty():
        value = click.get_text_stream("stdin").read()

    if value:
        value = value.strip()
        if conf.character_warning and len(value) > conf.character_warning:
            click.confirm("✂ Warning: Tweet is longer than {0} characters. Are you sure?".format(
                conf.character_warning), abort=True)
        return value
    else:
        raise click.BadArgumentUsage("Text can’t be empty.")

Example 18

Project: clustershell
Source File: Clush.py
View license
def bind_stdin(worker, display):
    """Create a stdin->port->worker binding: connect specified worker
    to stdin with the help of a reader thread and a ClusterShell Port
    object."""
    assert not sys.stdin.isatty()
    # Create a ClusterShell Port object bound to worker's task. This object
    # is able to receive messages in a thread-safe manner and then will safely
    # trigger ev_msg() on a specified event handler.
    port = worker.task.port(handler=StdInputHandler(worker), autoclose=True)
    # Launch a dedicated thread to read stdin in blocking mode. Indeed stdin
    # can be a file, so we cannot use a WorkerSimple here as polling on file
    # may result in different behaviors depending on selected engine.
    stdin_thread = threading.Thread(None, _stdin_thread_start, args=(port, display))
    # setDaemon because we're sometimes left with data that has been read and
    # ssh connection already closed.
    # Syntax for compat with Python < 2.6
    stdin_thread.setDaemon(True)
    stdin_thread.start()

Example 19

Project: crmsh
Source File: utils.py
View license
def can_ask():
    """
    Is user-interactivity possible?
    Checks if connected to a TTY.
    """
    return (not options.ask_no) and sys.stdin.isatty()

Example 20

Project: udiskie
Source File: prompt.py
View license
def password(password_command):
    """
    Create a password prompt function.

    :param bool hint_gui: whether a GUI input dialog should be preferred
    """
    gui = lambda: has_Gtk()          and get_password_gui
    tty = lambda: sys.stdin.isatty() and get_password_tty
    if password_command == 'builtin:gui':
        return gui() or tty()
    elif password_command == 'builtin:tty':
        return tty() or gui()
    elif password_command:
        return DeviceCommand(password_command)
    else:
        return None

Example 21

Project: crash
Source File: command.py
View license
def get_stdin():
    """
    Get data from stdin, if any
    """
    if not sys.stdin.isatty():
        for line in sys.stdin:
            yield line
    return

Example 22

Project: mycli
Source File: main.py
View license
def confirm_destructive_query(queries):
    """Check if the query is destructive and prompts the user to confirm.
    Returns:
    None if the query is non-destructive or we can't prompt the user.
    True if the query is destructive and the user wants to proceed.
    False if the query is destructive and the user doesn't want to proceed.
    """
    prompt_text = ("You're about to run a destructive command.\n"
                   "Do you want to proceed? (y/n)")
    if is_destructive(queries) and sys.stdin.isatty():
        return click.prompt(prompt_text, type=bool)

Example 23

Project: dcos-cli
Source File: main.py
View license
    @staticmethod
    def _assert_no_tty(command_example):
        if sys.stdin.isatty():
            # We don't support TTY right now.
            # In the future we will start an editor
            template = ("We currently don't support reading from the TTY. "
                        "Please specify an application JSON.\n{}")
            raise DCOSException(template.format(command_example))

Example 24

Project: GoogleSpeech
Source File: __init__.py
View license
  def __next__(self):
    """ Get a speech segment, splitting text by taking into account spaces, punctuation, and maximum segment size. """
    if self.text == "-":
      if sys.stdin.isatty():
        logging.getLogger().error("Stdin is not a pipe")
        return
      while True:
        new_line = sys.stdin.readline()
        if not new_line:
          return
        segments = __class__.splitText(new_line)
        for segment_num, segment in enumerate(segments):
          yield SpeechSegment(segment, self.lang, segment_num, len(segments))

    else:
      segments = __class__.splitText(self.text)
      for segment_num, segment in enumerate(segments):
        yield SpeechSegment(segment, self.lang, segment_num, len(segments))

Example 25

Project: ete
Source File: common.py
View license
def src_tree_iterator(args):
    if not args.src_trees and not sys.stdin.isatty():
        log.debug("Reading trees from standard input...")
        args.src_trees = sys.stdin
        
    if args.src_trees:
        for stree in args.src_trees:
            yield stree.strip()
    elif args.src_tree_list:
        for line in open(args.src_tree_list):
            line = line.strip()
            if line: 
                yield line

Example 26

Project: ete
Source File: ete.py
View license
def tree_iterator(args):
    if not args.src_trees and not sys.stdin.isatty():
        log.debug("Reading trees from standard input...")
        args.src_trees = sys.stdin
    elif not args.src_trees:
        log.error("At least one tree is required as input (i.e --src_trees ) ")
        sys.exit(-1)

    for stree in args.src_trees:
        # CHECK WHAT is needed before process the main command, allows mods before analyses
        yield stree.strip()

Example 27

Project: freeipa
Source File: cli.py
View license
    def prompt_password(self, label, confirm=True):
        """
        Prompt user for a password or read it in via stdin depending
        on whether there is a tty or not.
        """
        if sys.stdin.isatty():
            prompt = u'%s: ' % unicode(label)
            repeat_prompt = unicode(_('Enter %(label)s again to verify: ') % dict(label=label))
            while True:
                pw1 = self.prompt_helper(prompt, label, prompt_func=getpass.getpass)
                if not confirm:
                    return pw1
                pw2 = self.prompt_helper(repeat_prompt, label, prompt_func=getpass.getpass)
                if pw1 == pw2:
                    return pw1
                self.print_error( _('Passwords do not match!'))
        else:
            return self.decode(sys.stdin.readline().strip())

Example 28

Project: cot
Source File: cli.py
View license
    def parse_args(self, argv):
        """Parse the given CLI arguments into a namespace object.

        Args:
          argv (list): List of CLI arguments, not including argv0
        Returns:
          argparse.Namespace: Parser namespace object
        """
        # Parse the user input
        args = self.parser.parse_args(argv)

        # If being run non-interactively, treat as if --force is set, in order
        # to avoid hanging while trying to read input that will never come.
        if not (sys.stdin.isatty() and sys.stdout.isatty()):
            args._force = True  # pylint: disable=protected-access

        return args

Example 29

Project: grr
Source File: repacking.py
View license
  def GetSigningPassword(self):
    if sys.stdin.isatty():
      print "Enter passphrase for code signing:"
      return getpass.getpass()
    else:
      passwd = sys.stdin.readline().strip()
      if not passwd:
        raise RuntimeError("Expected signing password on stdin, got nothing.")
      return passwd

Example 30

Project: titan
Source File: titan_rpc.py
View license
def create_auth_func():
  """Default auth func."""
  email = ''
  password = ''
  if sys.stdin.isatty():
    email = raw_input('Email: ')
    password = getpass.getpass('Password: ')
  return lambda: (email, password)

Example 31

Project: selfspy
Source File: password_dialog.py
View license
def get_user_password(verify, message=None, force_save=False):
    if sys.stdin.isatty():
        pw = get_tty_password(verify, message, force_save)
    else:
        pw = get_tk_password(verify, message, force_save)

    return pw

Example 32

Project: svtools
Source File: utils.py
View license
    @staticmethod
    def valid(string):
        '''Check if we allow the opening of stdin'''
        if string is None and sys.stdin.isatty():
            raise IOError('no input specified but terminal is interactive')
        return True

Example 33

Project: svtools
Source File: varlookup.py
View license
def run_from_args(args):
    pass_prefix = "#"
    if args.aFile == None:
        if sys.stdin.isatty():
            sys.stderr.write('Please stream in input to this command or specify the file to read\n')
            sys.exit(1)
        else:
            args.aFile = sys.stdin

    try:
        varLookup(args.aFile, args.bFile, args.output, args.max_distance, pass_prefix, args.cohort_name)
    except IOError as err:
        sys.stderr.write("IOError " + str(err) + "\n");

Example 34

Project: meocloud-cli
Source File: handler.py
View license
    def get_input(self):
        if not sys.stdin.isatty():
            log.warning('CLI: Must get input but stdin is not a terminal.')
            self.out()
            self.out('ERROR: Must get input but stdin is not a terminal.')
            self.stop(quiet=True)
            self.out('Goodbye!')
            sys.exit(1)
        return input().strip()

Example 35

Project: docker-lamp
Source File: lamp.py
View license
    def console(self, vm: str, user: str):
        self.check_vms_are_running()

        vm_name = self.get_vm_item(vm, 'name')
        if vm_name == '':
            raise Exception('{} does not seem to be in your services or has crashed'.format(vm))

        tty = 't' if sys.stdin.isatty() else ''
        subprocess.call(['docker', 'exec', '-u', user, '-i' + tty, vm_name, 'env', 'TERM=xterm', 'bash'])

Example 36

Project: docker-lamp
Source File: lamp.py
View license
    def run_php(self, user: str, args: str):
        self.check_vms_are_running()

        tty = 't' if sys.stdin.isatty() else ''
        cmd = ['docker', 'exec', '-u', user, '-i' + tty, self.get_vm_item('php', 'name'), 'bash', '-c', '--']
        cmd += ['cd /var/' + self.current_dir_relative + '; exec /usr/bin/php ' + args]
        subprocess.call(cmd, stdin=sys.stdin)

Example 37

Project: docker-lamp
Source File: lamp.py
View license
    def run_mysql(self, args: str):
        self.check_vms_are_running()

        vm_name = self.get_vm_item('mysql', 'name')
        if vm_name == '':
            raise Exception('mysql does not seem to be in your services or has crashed')

        tty = 't' if sys.stdin.isatty() else ''
        password = self.user_config_main.get(
            'mysql.root_password',
            self.default_config_main.get('mysql.root_password')
        )
        cmd = ['docker', 'exec', '-u', 'root', '-i' + tty, vm_name]
        cmd += ['mysql', '-u', 'root', '-p' + password, args]
        subprocess.call(cmd, stdin=sys.stdin)

Example 38

Project: alertlib
Source File: alert.py
View license
def main(argv):
    parser = setup_parser()
    args = parser.parse_args(argv)

    if sys.stdin.isatty():
        print >>sys.stderr, '>> Enter the message to alert, then hit control-D'
    message = sys.stdin.read().strip()

    if args.dry_run:
        alertlib.enter_test_mode()
        logging.getLogger().setLevel(logging.INFO)

    alert(message, args)

Example 39

Project: xmpptalk
Source File: commands.py
View license
@command('debug', _('suspend and open debug console'), PERM_SYSADMIN)
def do_debug(self, arg):
  if sys.stdin.isatty():
    import builtins
    from cli import repl
    from pyxmpp2.jid import JID
    old_ = builtins._
    g = locals()
    del g['repl'], g['builtins'], g['old_'], g['arg']
    repl(g, 'cmd.txt')
    builtins._ = old_
  else:
    self.reply(_('Error: stdin is not terminal.'))
  return True

Example 40

Project: xmpptalk
Source File: commands.py
View license
@command('debug', _('suspend and open debug console'), PERM_SYSADMIN)
def do_debug(self, arg):
  if sys.stdin.isatty():
    import builtins
    from cli import repl
    from pyxmpp2.jid import JID
    old_ = builtins._
    g = locals()
    del g['repl'], g['builtins'], g['old_'], g['arg']
    repl(g, 'cmd.txt')
    builtins._ = old_
  else:
    self.reply(_('Error: stdin is not terminal.'))
  return True

Example 41

Project: ansible
Source File: vault.py
View license
    def execute_encrypt(self):

        if len(self.args) == 0 and sys.stdin.isatty():
            display.display("Reading plaintext input from stdin", stderr=True)

        for f in self.args or ['-']:
            self.editor.encrypt_file(f, output_file=self.options.output_file)

        if sys.stdout.isatty():
            display.display("Encryption successful", stderr=True)

Example 42

Project: ansible
Source File: vault.py
View license
    def execute_decrypt(self):

        if len(self.args) == 0 and sys.stdin.isatty():
            display.display("Reading ciphertext input from stdin", stderr=True)

        for f in self.args or ['-']:
            self.editor.decrypt_file(f, output_file=self.options.output_file)

        if sys.stdout.isatty():
            display.display("Decryption successful", stderr=True)

Example 43

Project: ansible
Source File: vault.py
View license
    def execute_encrypt(self):

        if len(self.args) == 0 and sys.stdin.isatty():
            display.display("Reading plaintext input from stdin", stderr=True)

        for f in self.args or ['-']:
            self.editor.encrypt_file(f, output_file=self.options.output_file)

        if sys.stdout.isatty():
            display.display("Encryption successful", stderr=True)

Example 44

Project: ansible
Source File: vault.py
View license
    def execute_decrypt(self):

        if len(self.args) == 0 and sys.stdin.isatty():
            display.display("Reading ciphertext input from stdin", stderr=True)

        for f in self.args or ['-']:
            self.editor.decrypt_file(f, output_file=self.options.output_file)

        if sys.stdout.isatty():
            display.display("Decryption successful", stderr=True)

Example 45

Project: pyfs
Source File: scriptsupport.py
View license
def run_for_input(what, args):
    if not sys.stdin.isatty():
        stdin_idx = args.index("-") if "-" in args else None
        for line in get_line_from_stdin():
            element = decode_input(line)
            funcargs = decode_strings(args)
            if stdin_idx is not None:
                funcargs[stdin_idx:stdin_idx+1] = [element]
            else:
                funcargs[0:0] = [element]
            return run_with(what, funcargs)
    else:
        return run_with(what, decode_strings(args))

Example 46

Project: jaide
Source File: cli.py
View license
def run():
    if os.name == 'posix' and sys.stdin.isatty():
        # set max_content_width to the width of the terminal dynamically
        rows, columns = popen('stty size', 'r').read().split()
        # obj and max_column_width get passed into click, and don't actually
        # proceed into the main() command group. Click handles the CLI
        # user options and passing them into main().
        main(obj={}, max_content_width=int(columns))
    else:
        main(obj={})

Example 47

Project: python-glanceclient
Source File: shell.py
View license
def _is_image_data_provided(args):
    """Return True if some image data has probably been provided by the user"""
    # NOTE(kragniz): Check stdin works, then check is there is any data
    # on stdin or a filename has been provided with --file
    try:
        os.fstat(0)
    except OSError:
        return False
    return not sys.stdin.isatty() or args.file or args.copy_from

Example 48

Project: s3ql
Source File: common.py
View license
def get_backend_factory(storage_url, backend_options, authfile,
                        compress=('lzma', 2), raw=False):
    '''Return factory producing backend objects for given storage-url

    If *raw* is true, don't attempt to unlock and don't wrap into
    ComprencBackend.
    '''

    from .backends import prefix_map
    from .backends.common import (CorruptedObjectError, NoSuchObject, AuthenticationError,
                                  DanglingStorageURLError, AuthorizationError)
    from .backends.comprenc import ComprencBackend

    hit = re.match(r'^([a-zA-Z0-9]+)://', storage_url)
    if not hit:
        raise QuietError('Unable to parse storage url "%s"' % storage_url,
                         exitcode=2)

    backend = hit.group(1)
    try:
        backend_class = prefix_map[backend]
    except KeyError:
        raise QuietError('No such backend: %s' % backend, exitcode=11)

    # Validate backend options
    for opt in backend_options.keys():
        if opt not in backend_class.known_options:
            raise QuietError('Unknown backend option: %s' % opt,
                             exitcode=3)

    # Read authfile
    config = configparser.ConfigParser()
    if os.path.isfile(authfile):
        mode = os.stat(authfile).st_mode
        if mode & (stat.S_IRGRP | stat.S_IROTH):
            raise QuietError("%s has insecure permissions, aborting." % authfile,
                             exitcode=12)
        config.read(authfile)

    backend_login = None
    backend_passphrase = None
    fs_passphrase = None
    for section in config.sections():
        def getopt(name):
            try:
                return config.get(section, name)
            except configparser.NoOptionError:
                return None

        pattern = getopt('storage-url')

        if not pattern or not storage_url.startswith(pattern):
            continue

        backend_login = getopt('backend-login') or backend_login
        backend_passphrase = getopt('backend-password') or backend_passphrase
        fs_passphrase = getopt('fs-passphrase') or fs_passphrase

    if not backend_login and backend_class.needs_login:
        if sys.stdin.isatty():
            backend_login = getpass("Enter backend login: ")
        else:
            backend_login = sys.stdin.readline().rstrip()

    if not backend_passphrase and backend_class.needs_login:
        if sys.stdin.isatty():
            backend_passphrase = getpass("Enter backend passphrase: ")
        else:
            backend_passphrase = sys.stdin.readline().rstrip()

    backend = None
    try:
        backend = backend_class(storage_url, backend_login, backend_passphrase,
                                backend_options)

        # Do not use backend.lookup(), this would use a HEAD request and
        # not provide any useful error messages if something goes wrong
        # (e.g. wrong credentials)
        backend.fetch('s3ql_passphrase')

    except AuthenticationError:
        raise QuietError('Invalid credentials (or skewed system clock?).',
                         exitcode=14)

    except AuthorizationError:
        raise QuietError('No permission to access backend.',
                         exitcode=15)

    except HostnameNotResolvable:
        raise QuietError("Can't connect to backend: unable to resolve hostname",
                         exitcode=19)

    except DanglingStorageURLError as exc:
        raise QuietError(str(exc), exitcode=16)

    except NoSuchObject:
        encrypted = False

    else:
        encrypted = True

    finally:
        if backend is not None:
            backend.close()

    if raw:
        return lambda: backend_class(storage_url, backend_login, backend_passphrase,
                                     backend_options)

    if encrypted and not fs_passphrase:
        if sys.stdin.isatty():
            fs_passphrase = getpass("Enter file system encryption passphrase: ")
        else:
            fs_passphrase = sys.stdin.readline().rstrip()
    elif not encrypted:
        fs_passphrase = None

    if fs_passphrase is not None:
        fs_passphrase = fs_passphrase.encode('utf-8')

    if not encrypted:
        return lambda: ComprencBackend(None, compress,
                                    backend_class(storage_url, backend_login,
                                                  backend_passphrase, backend_options))

    with ComprencBackend(fs_passphrase, compress, backend) as tmp_backend:
        try:
            data_pw = tmp_backend['s3ql_passphrase']
        except CorruptedObjectError:
            raise QuietError('Wrong file system passphrase', exitcode=17)

    # To support upgrade, temporarily store the backend
    # passphrase in every backend object.
    def factory():
        b = ComprencBackend(data_pw, compress,
                            backend_class(storage_url, backend_login,
                                          backend_passphrase, backend_options))
        b.fs_passphrase = fs_passphrase
        return b

    return factory

Example 49

Project: free_tls_certificates
Source File: driver.py
View license
def stop_if_certificate_valid(opts):
    # Stop if the certificate is already valid for all of the domains.
    import idna

    if not os.path.exists(opts["certificate_fn"]):
        if sys.stdin.isatty():
           sys.stderr.write("Certificate file %s not present...\n" % opts["certificate_fn"])
        return

    def idna_encode(domain):
        # squash exceptions here
        try:
            return idna.encode(domain).decode("ascii")
        except:
            return domain

    # Load the certificate.
    from free_tls_certificates.utils import load_certificate, get_certificate_domains
    cert = load_certificate(opts["certificate_fn"])

    # If this is a self-signed certificate (and the user is seeking
    # a real one), provision a new one.
    if cert.issuer == cert.subject and not opts["self_signed"]:
        if sys.stdin.isatty():
           sys.stderr.write("Replacing self-signed certificate...\n")
        return

    # If this is expiring within 30 days, provision a new one.
    expires_in = cert.not_valid_after - datetime.datetime.now()
    if expires_in < datetime.timedelta(days=30):
        if sys.stdin.isatty():
           sys.stderr.write("Replacing expiring certificate (expires in %s)...\n" % str(expires_in))
        return

    # If the certificate is not valid for one of the domains we're requesting,
    # provision a new one.
    request_domains = set(idna_encode(domain) for domain in opts["domains"])
    cert_domains = set(get_certificate_domains(cert))
    if len(request_domains - cert_domains) > 0:
        if sys.stdin.isatty():
           sys.stderr.write("Certificate is not valid for %s (found %s)...\n" % (
               ", ".join(request_domains - cert_domains),
               ", ".join(cert_domains)
               ))
        return

    # Certificate is valid for the requested domains - no need to provision.
    if sys.stdout.isatty():
        print("Certificate is already valid and good for at least 30 days.")
    sys.exit(3)

Example 50

Project: free_tls_certificates
Source File: driver.py
View license
def stop_if_certificate_valid(opts):
    # Stop if the certificate is already valid for all of the domains.
    import idna

    if not os.path.exists(opts["certificate_fn"]):
        if sys.stdin.isatty():
           sys.stderr.write("Certificate file %s not present...\n" % opts["certificate_fn"])
        return

    def idna_encode(domain):
        # squash exceptions here
        try:
            return idna.encode(domain).decode("ascii")
        except:
            return domain

    # Load the certificate.
    from free_tls_certificates.utils import load_certificate, get_certificate_domains
    cert = load_certificate(opts["certificate_fn"])

    # If this is a self-signed certificate (and the user is seeking
    # a real one), provision a new one.
    if cert.issuer == cert.subject and not opts["self_signed"]:
        if sys.stdin.isatty():
           sys.stderr.write("Replacing self-signed certificate...\n")
        return

    # If this is expiring within 30 days, provision a new one.
    expires_in = cert.not_valid_after - datetime.datetime.now()
    if expires_in < datetime.timedelta(days=30):
        if sys.stdin.isatty():
           sys.stderr.write("Replacing expiring certificate (expires in %s)...\n" % str(expires_in))
        return

    # If the certificate is not valid for one of the domains we're requesting,
    # provision a new one.
    request_domains = set(idna_encode(domain) for domain in opts["domains"])
    cert_domains = set(get_certificate_domains(cert))
    if len(request_domains - cert_domains) > 0:
        if sys.stdin.isatty():
           sys.stderr.write("Certificate is not valid for %s (found %s)...\n" % (
               ", ".join(request_domains - cert_domains),
               ", ".join(cert_domains)
               ))
        return

    # Certificate is valid for the requested domains - no need to provision.
    if sys.stdout.isatty():
        print("Certificate is already valid and good for at least 30 days.")
    sys.exit(3)