def ipexec(fname, options=None, commands=()): """Utility to call 'ipython filename'. Starts IPython with a minimal and safe configuration to make startup as fast as possible. Note that this starts IPython in a subprocess! Parameters ---------- fname : str, Path Name of file to be executed (should have .py or .ipy extension). options : optional, list Extra command-line flags to be passed to IPython. commands : optional, list Commands to send in on stdin Returns ------- ``(stdout, stderr)`` of ipython subprocess. """ __tracebackhide__ = True if options is None: options = [] cmdargs = default_argv() + options test_dir = os.path.dirname(__file__) ipython_cmd = get_ipython_cmd() # Absolute path for filename full_fname = os.path.join(test_dir, fname) full_cmd = ipython_cmd + cmdargs + ['--', full_fname] env = os.environ.copy() # FIXME: ignore all warnings in ipexec while we have shims # should we keep suppressing warnings here, even after removing shims? env['PYTHONWARNINGS'] = 'ignore' # env.pop('PYTHONWARNINGS', None) # Avoid extraneous warnings appearing on stderr # Prevent coloring under PyCharm ("\x1b[0m" at the end of the stdout) env.pop("PYCHARM_HOSTED", None) for k, v in env.items(): # Debug a bizarre failure we've seen on Windows: # TypeError: environment can only contain strings if not isinstance(v, str): print(k, v) p = Popen(full_cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env) out, err = p.communicate( input=py3compat.encode('\n'.join(commands)) or None) out, err = py3compat.decode(out), py3compat.decode(err) # `import readline` causes 'ESC[?1034h' to be output sometimes, # so strip that out before doing comparisons if out: out = re.sub(r'\x1b\[[^h]+h', '', out) return out, err
def passwd(passphrase=None, algorithm='sha1'): """Generate hashed password and salt for use in notebook configuration. In the notebook configuration, set `c.NotebookApp.password` to the generated string. Parameters ---------- passphrase : str Password to hash. If unspecified, the user is asked to input and verify a password. algorithm : str Hashing algorithm to use (e.g, 'sha1' or any argument supported by :func:`hashlib.new`). Returns ------- hashed_passphrase : str Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. Examples -------- >>> passwd('mypassword') 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12' """ if passphrase is None: for i in range(3): p0 = getpass.getpass('Enter password: '******'Verify password: '******'Passwords do not match.') else: raise UsageError('No matching passwords found. Giving up.') h = hashlib.new(algorithm) salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len) h.update(encode(passphrase, 'utf-8') + encode(salt, 'ascii')) return ':'.join((algorithm, salt, h.hexdigest()))
def passwd(passphrase=None, algorithm='sha1'): """Generate hashed password and salt for use in notebook configuration. In the notebook configuration, set `c.NotebookApp.password` to the generated string. Parameters ---------- passphrase : str Password to hash. If unspecified, the user is asked to input and verify a password. algorithm : str Hashing algorithm to use (e.g, 'sha1' or any argument supported by :func:`hashlib.new`). Returns ------- hashed_passphrase : str Hashed password, in the format 'hash_algorithm:salt:passphrase_hash'. Examples -------- >>> passwd('mypassword') 'sha1:7cf3:b7d6da294ea9592a9480c8f52e63cd42cfb9dd12' # random """ if passphrase is None: for i in range(3): p0 = getpass.getpass('Enter password: '******'Verify password: '******'Passwords do not match.') else: raise UsageError('No matching passwords found. Giving up.') h = hashlib.new(algorithm) salt = ('%0' + str(salt_len) + 'x') % random.getrandbits(4 * salt_len) h.update(encode(passphrase, 'utf-8') + encode(salt, 'ascii')) return ':'.join((algorithm, salt, h.hexdigest()))
def passwd_check(hashed_passphrase, passphrase): """Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- >>> from IPython.lib.security import passwd_check >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ... 'mypassword') True >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ... 'anotherpassword') False """ try: algorithm, salt, pw_digest = hashed_passphrase.split(':', 2) except (ValueError, TypeError): return False try: h = hashlib.new(algorithm) except ValueError: return False if len(pw_digest) == 0: return False h.update(encode(passphrase, 'utf-8') + encode(salt, 'ascii')) return h.hexdigest() == pw_digest
def passwd_check(hashed_passphrase, passphrase): """Verify that a given passphrase matches its hashed version. Parameters ---------- hashed_passphrase : str Hashed password, in the format returned by `passwd`. passphrase : str Passphrase to validate. Returns ------- valid : bool True if the passphrase matches the hash. Examples -------- >>> from IPython.lib.security import passwd_check >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ... 'mypassword') True >>> passwd_check('sha1:0e112c3ddfce:a68df677475c2b47b6e86d0467eec97ac5f4b85a', ... 'anotherpassword') False """ try: algorithm, salt, pw_digest = hashed_passphrase.split(':', 2) except (ValueError, TypeError): return False try: h = hashlib.new(algorithm) except ValueError: return False if len(pw_digest) == 0: return False h.update(encode(passphrase, 'utf-8') + encode(salt, 'ascii')) return h.hexdigest() == pw_digest
def ipexec(fname, options=None, commands=()): """Utility to call 'ipython filename'. Starts IPython with a minimal and safe configuration to make startup as fast as possible. Note that this starts IPython in a subprocess! Parameters ---------- fname : str Name of file to be executed (should have .py or .ipy extension). options : optional, list Extra command-line flags to be passed to IPython. commands : optional, list Commands to send in on stdin Returns ------- ``(stdout, stderr)`` of ipython subprocess. """ if options is None: options = [] cmdargs = default_argv() + options test_dir = os.path.dirname(__file__) ipython_cmd = get_ipython_cmd() # Absolute path for filename full_fname = os.path.join(test_dir, fname) full_cmd = ipython_cmd + cmdargs + [full_fname] env = os.environ.copy() # FIXME: ignore all warnings in ipexec while we have shims # should we keep suppressing warnings here, even after removing shims? env['PYTHONWARNINGS'] = 'ignore' # env.pop('PYTHONWARNINGS', None) # Avoid extraneous warnings appearing on stderr for k, v in env.items(): # Debug a bizarre failure we've seen on Windows: # TypeError: environment can only contain strings if not isinstance(v, str): print(k, v) p = Popen(full_cmd, stdout=PIPE, stderr=PIPE, stdin=PIPE, env=env) out, err = p.communicate(input=py3compat.encode('\n'.join(commands)) or None) out, err = py3compat.decode(out), py3compat.decode(err) # `import readline` causes 'ESC[?1034h' to be output sometimes, # so strip that out before doing comparisons if out: out = re.sub(r'\x1b\[[^h]+h', '', out) return out, err
def _write(self, input): """Write input to AMPL""" stdin = self.process.stdin stdin.write(py3compat.encode("%d " % len(input), 'utf8')) stdin.write(py3compat.encode(input, 'utf8')) stdin.flush()