def set_password(): """Ask user for password, store it in notebook json configuration file""" print("First choose a password.") hashedpw = passwd() print("We will store your password encrypted in the notebook configuration file: ") print(hashedpw) with persist_config() as config: config.NotebookApp.password = hashedpw print('... done\n')
def setup_notebook(port): # if the profile doesn't exist, create it -- otherwise we've probably # already done this step if not exists(jupyter_config_path): # get a password from notebook.auth import passwd print(bc.WARNING + '[setup_notebook] '+bc.ENDC+'This script will create a Jupyter notebook profile for working remotely') print(bc.WARNING + '[setup_notebook] '+bc.ENDC+'When it is finished, you can find the configuration in %s\n'%(bc.UNDERLINE + jupyter_config_path + bc.ENDC)) print(bc.WARNING + '[setup_notebook] '+bc.ENDC+'First, we need a *new* password for your Jupyter notebook\n') new_pass = passwd() print(bc.WARNING + '[setup_notebook] '+bc.ENDC+'Creating an SSL certificate to enable a secure connection\nThe certificate will be in your ~/.ssh directory\n') # make sure the .ssh directory is there before continuing sshdir = '{home}/.ssh'.format(home=home) if not os.path.exists(sshdir): os.makedirs(sshdir) os.fchmod(sshdir, 700) # make an ssl certificate certfile = "{home}/.ssh/notebook_cert.pem".format(home=home) out = subprocess.check_output(['openssl', 'req', '-x509', '-nodes', '-days', '365', '-newkey', 'rsa:1024', '-keyout', '%s'%certfile, '-out', '%s'%certfile, '-batch'], stderr=subprocess.STDOUT) lines = out.split('\n') for l in lines : print(bc.OKGREEN + '[openssl] ' + bc.ENDC + l) # write the notebook config # create the directory os.makedirs(jupyter_config_path) with open("{profile_path}/jupyter_notebook_config.py".format(profile_path=jupyter_config_path), 'w') as f: f.write(notebook_config_template.format( password=new_pass, certfile=certfile, port=port)) print(bc.WARNING + '[setup_notebook] '+ bc.BOLD + 'Notebook setup complete' + bc.ENDC) else: print(bc.FAIL + "The jupyter notebook already looks set up -- if this is not the case, delete {dir} and run the script again.".format(dir=jupyter_config_path) + bc.ENDC)
def set_password(args): password = args.password while not password : password1 = getpass("" if args.quiet else "Provide password: "******"" if args.quiet else "Repeat password: "******"Passwords do not match, try again") elif len(password1) < 4: print("Please provide at least 4 characters") else: password = password1 password_hash = passwd(password) cfg = BaseJSONConfigManager(config_dir=jupyter_config_dir()) cfg.update('jupyter_notebook_config', { 'NotebookApp': { 'password': password_hash, } }) if not args.quiet: print("password stored in config dir: %s" % jupyter_config_dir())
# https://jupyter-notebook.readthedocs.io/en/stable/config.html from os import environ from notebook.auth import passwd _pw = environ.get("PASSWORD") c.NotebookApp.ip = '0.0.0.0' c.NotebookApp.port = 80 c.NotebookApp.allow_root = True c.NotebookApp.open_browser = False c.NotebookApp.password = "" if _pw is None else passwd(_pw) c.NotebookApp.token = ""
from notebook.auth import passwd print('generate password..') pw = passwd('demo') print('default password generated:' + pw) print('write to config') with open('/root/.jupyter/jupyter_notebook_config.py', 'a') as f: f.write("c.NotebookApp.password = u'" + pw + "'") print('setting jupyter password done!')
# Whether to open in a browser after starting. The specific browser used is # platform dependent and determined by the python standard library `webbrowser` # module, unless it is overridden using the --browser (NotebookApp.browser) # configuration option. c.NotebookApp.open_browser = False # Hashed password to use for web authentication. # # To generate, type in a python/IPython shell: # # from notebook.auth import passwd; passwd() # # The string should be of the form type:salt:hashed-password. if 'PASSWORD' in os.environ: from notebook.auth import passwd c.NotebookApp.password = passwd(os.environ['PASSWORD']) del os.environ['PASSWORD'] # The port the notebook server will listen on. c.NotebookApp.port = 8888 # The number of additional ports to try if the specified port is not available. # c.NotebookApp.port_retries = 50 # DISABLED: use %pylab or %matplotlib in the notebook to enable matplotlib. # c.NotebookApp.pylab = 'disabled' # Reraise exceptions encountered loading server extensions? # c.NotebookApp.reraise_server_extension_failures = False # Python modules to load as notebook server extensions. This is an experimental
# Script to create a password for the Jupyter notebook configuration # # Written by Pieter de Rijk <*****@*****.**> # from notebook.auth import passwd import os jupyter_config = os.path.expanduser('~/.jupyter/jupyter_notebook_config.py') line = "===========================================================================" print line print "Setting Jupyter additional configuration" print line print "Please set a strong password" pwhash = passwd() print line print "Following will be added to %s " % (jupyter_config) jupyter_comment_start = "# Start of lines added by jupyter-password.py" jupyter_comment_end = "# End lines added by jupyter-passwordd.py" jupyter_passwd_line = "c.NotebookApp.password = u'%s'" % (pwhash) jupyter_no_browser = "c.NotebookApp.open_browser = False" print " " print " %s " % (jupyter_comment_start) print " %s " % (jupyter_passwd_line) print " %s " % (jupyter_no_browser) print " %s " % (jupyter_comment_end) print line
def pwline(): pwstr = environ.get('JUPYTER_PASSWORD') if pwstr: return r"c.NotebookApp.password = '******'".format(passwd(pwstr)) else: return ''
from notebook.auth import passwd outfile = open("./jupyter_notebook_config.py", "w") outfile.write("c.NotebookApp.password = u\"%s\"" % passwd(open("my_secret.txt", "r").read())) outfile.close()
#/usr/bin/env python from notebook.auth import passwd import sys try: password = sys.argv[1] print(passwd(password)) except Exception as e: pass
port, password = os.getenv("JUPYTER_Port"), os.getenv("JUPYTER_Password") if port == "" or password == "": sys.exit("JUPYTER_Port or JUPYTER_Password is unset.") # dirpath = os.path.dirname(os.path.abspath(sys.argv[0])) dirpath = os.getcwd() ret = subprocess.run(["jupyter", "notebook", "--generate-config", "-y"]) if ret.returncode != 0: sys.exit(1) appendLines = """ c.NotebookApp.open_browser = False c.NotebookApp.allow_root = True c.NotebookApp.allow_origin = '*' c.NotebookApp.ip = '0.0.0.0' c.NotebookApp.port = %s """ % port pemFile = os.path.join(dirpath, "jupyter.pem") keyFile = os.path.join(dirpath, "jupyter.key") if os.path.isfile(pemFile) and os.path.isfile(keyFile): appendLines += ("c.NotebookApp.certfile = u'%s'\n" % pemFile) appendLines += ("c.NotebookApp.keyfile = u'%s'\n" % keyFile) appendLines += ("c.NotebookApp.password = u'%s'\n" % passwd(password)) script = os.path.expanduser("~/.jupyter/jupyter_notebook_config.py") with open(script, "a") as f: f.write(appendLines)
# platform dependent and determined by the python standard library `webbrowser` # module, unless it is overridden using the --browser (NotebookApp.browser) # configuration option. c.NotebookApp.open_browser = False ## Hashed password to use for web authentication. # # To generate, type in a python/IPython shell: # # from notebook.auth import passwd; passwd() # # The string should be of the form type:salt:hashed-password. #c.NotebookApp.password = '' if 'JUPYTER_PASSWORD' in os.environ: c.NotebookApp.password = passwd(os.environ['JUPYTER_PASSWORD']) del os.environ['JUPYTER_PASSWORD'] ## The port the notebook server will listen on. c.NotebookApp.port = int(os.getenv('JUPYTER_PORT', 3000)) ## Token used for authenticating first-time connections to the server. # # When no password is enabled, the default is to generate a new, random token. # # Setting to an empty string disables authentication altogether, which is NOT # RECOMMENDED. c.NotebookApp.token = '' ## The base name used when creating untitled directories. c.ContentsManager.untitled_directory = 'New Folder'
import os home_dir = os.environ['HOME'] os.system("jupyter notebook --generate-config") from notebook.auth import passwd pwsha = passwd() config_str = """ # Server config c.NotebookApp.ip = '0.0.0.0' c.NotebookApp.open_browser = False c.NotebookApp.password = u'{}' # It is a good idea to put it on a known, fixed port c.NotebookApp.port = 8888 c.NotebookApp.notebook_dir = u'/root/' c.NotebookApp.allow_root = True """.format(pwsha) with open(home_dir + "/.jupyter/jupyter_notebook_config.py", "w") as cf: cf.write(config_str)
import stat import subprocess from shutil import copyfile from jupyter_core.paths import jupyter_data_dir from notebook.auth import passwd # Only (pre)set a password if we're *not* using OpenID Connect if not (os.getenv('OIDC_DISCOVERY_URI') and os.getenv('OIDC_CLIENT_ID')): # Set Jupyter Notebook Server password to 'jupyter-<Marathon-App-Prefix>' # e.g., Marathon App ID '/foo/bar/app' maps to password: '******' if os.getenv('MARATHON_APP_ID'): MARATHON_APP_PREFIX = \ '-'.join(os.getenv('MARATHON_APP_ID').split('/')[:-1]) c.NotebookApp.password = passwd( 'jupyter{}'.format(MARATHON_APP_PREFIX)) # Set a password if JUPYTER_PASSWORD (override) is set if os.getenv('JUPYTER_PASSWORD'): c.NotebookApp.password = passwd(os.getenv('JUPYTER_PASSWORD')) del (os.environ['JUPYTER_PASSWORD']) else: # Disable Notebook authentication since we're authenticating using OpenID Connect c.NotebookApp.password = u'' c.NotebookApp.token = u'' # Don't leak OpenID Connect configuration to the end-user for env in [ 'OIDC_DISCOVERY_URI', 'OIDC_REDIRECT_URI', 'OIDC_CLIENT_ID', 'OIDC_CLIENT_SECRET', 'OIDC_EMAIL' ]:
from notebook.auth import passwd print(passwd())
#!/usr/bin/env python from notebook.auth import passwd print(passwd())
from notebook.auth import passwd hashstr = passwd() print (hashstr)
def generate_hash(password): from notebook.auth import passwd return passwd(password)
# # #### securing the notebook #### # # If you are running the notebook on a shared system, such as NSC. It is good that you secure it using a password and turn on encryption (https). Below is an extract from http://jupyter-notebook.readthedocs.io/en/stable/public_server.html#notebook-server-security on how to do that. # # First generate a config file you do not already have one. # ``` # jupyter notebook --generate-config # # ``` # Prepare a hashed password using the following code: # In[ ]: from notebook.auth import passwd passwd() # #### making .py and .html conversion automatically when saving the notebook # # Reference: https://svds.com/jupyter-notebook-best-practices-for-data-science/ # # Put the following at the top of `jupyter_notebook_config.py` file: # # ``` python # import os # from subprocess import check_call # # def post_save(model, os_path, contents_manager): # """post-save hook for converting notebooks to .py scripts""" # if model['type'] != 'notebook':
for target in args.targets: if target == "main": if args.password: print( "Unable to use the password passed as paramter, querying interactively", file=sys.stderr) print("Enter a password for the current unix user:"******"passwd") if r == 0: print("Password updated", file=sys.stderr) else: print("Failure updating password", file=sys.stderr) elif target == "lab": from notebook.auth import passwd if args.password: lab_passwd_hash = passwd(args.password) else: print("Enter a password for the JupyterLab environment:") lab_passwd_hash = passwd() r = os.system("lamachine-config lab_password_sha1 \"" + lab_passwd_hash + "\"") if r == 0: print( "Password scheduled to update, please run lamachine-update now", file=sys.stderr) else: print("Failured to set password", sys.stderr) elif target == "flat": if args.password: pw = args.password else:
def get_password(): return passwd(None, 'sha512')
import os from notebook.auth import passwd passwd = passwd(os.environ.get('NOTEBOOK_PASSWORD', '')) passwd = "c.NotebookApp.password = u'{passwd}'".format(passwd=passwd) print(passwd)
from notebook.auth import passwd p=passwd() with open("/home/ubuntu/.jupyter/jupyter_notebook_config.py","a") as f: f.write("c.NotebookApp.password = '******'".format(p))
def get_pw(): notebook_pw = os.environ['NOTEBOOK_PASSWORD'] return passwd(notebook_pw)
#!/usr/local/bin/ipython3 from notebook.auth import passwd import os import sys home = os.getenv('HOME') notebook_dir = os.path.join(home, 'notebooks') try: os.makedirs(notebook_dir) except: #exists pass pwd = passwd() with open(os.path.join(home, '.jupyter/jupyter_notebook_config.py'), 'a') as f: f.write('\n') f.write('c.NotebookApp.password = {}\n'.format(repr(pwd))) f.write("c.NotebookApp.certfile = {}\n".format(repr(os.path.join(home, '.jupyter/sign.pem')))) f.write("c.NotebookApp.keyfile = {}\n".format(repr(os.path.join(home, '.jupyter/sign.key')))) f.write("c.NotebookApp.notebook_dir = {}\n".format(repr(notebook_dir)))
import os from notebook.auth import passwd c = get_config() c.NotebookApp.ip = '0.0.0.0' c.NotebookApp.open_browser = False c.NotebookApp.port = 8888 if os.environ.get('PASSWORD', 'none') != 'none': c.NotebookApp.password = passwd( os.environ['PASSWORD'] ) del os.environ['PASSWORD'] else: c.NotebookApp.password = passwd( "biospin1!" )
if os.path.isdir("$HOME/.jupyter/profile_nbserver")is False: os.system("ipython profile create nbserver") else: os.system("echo profile_nbserver is already exist.") yes = set(['yes','y', 'ye', '']) no = set(['no','n']) print ("Do you want to reset password? (y/n)") choice = raw_input().lower() if choice in yes: from notebook.auth import passwd pwsha = passwd() config_str = """ # Server config c = get_config() c.NotebookApp.ip = '*' c.NotebookApp.open_browser = False c.NotebookApp.password = u'{}' # It is a good idea to put it on a known, fixed port c.NotebookApp.port = 8888 c.NotebookApp.notebookr_dir = u'/home/biadmin/' """.format(pwsha) #elif choice in no: #else: #print("Please respond with 'y' or 'n'")
CONFFILE = "{{source_path}}/LaMachine/host_vars/{{hostname}}.yml" if __name__ == '__main__': parser = argparse.ArgumentParser(description="Interactive tool to set a password for one or more components of LaMachine", formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('targets', nargs='+', help='Targets, valid are: main (e.g. for ssh), lab (for jupyterlab)') args = parser.parse_args() for target in args.targets: if target == "main": print("Enter a password for the current unix user:"******"passwd") if r != 0: print("Password updated",file=sys.stderr) else: print("Failure updating password",file=sys.stderr) elif target == "lab": from notebook.auth import passwd print("Enter a password for the JupyterLab environment:") lab_passwd_hash = passwd() r = os.system("sed -i.bak 's/lab_password_sha1.*/lab_password_sha1: \"" + lab_passwd_hash + "\"/' " + CONFFILE) if r != 0: #no lab password yet? append with open(CONFFILE,'a','utf-8') as f: print('lab_password_sha1: "' + lab_passwd_hash + '"') print("Password scheduled to update, please run lamachine-update now",file=sys.stderr) else: print("No such target: ", target,file=sys.stderr)
cert.gmtime_adj_notBefore(0) cert.gmtime_adj_notAfter(365 * 24 * 60 * 60) cert.set_issuer(cert.get_subject()) cert.set_pubkey(k) cert.sign(k, "sha256") with io.open(join(cert_dir, certfile), "wt") as f: f.write(crypto.dump_certificate(crypto.FILETYPE_PEM, cert).decode("utf8")) with io.open(join(cert_dir, keyfile), "wt") as f: f.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, k).decode("utf8")) if __name__ == "__main__": print("This guide you into securing your notebook server") print("first choose a password.") pw = passwd() print("We will store your password encrypted in the notebook configuration file: ") print(pw) loader = JSONFileConfigLoader("jupyter_notebook_config.json", jupyter_config_dir()) try: config = loader.load_config() except ConfigFileNotFound: config = Config() config.NotebookApp.password = pw with io.open(os.path.join(jupyter_config_dir(), "jupyter_notebook_config.json"), "w") as f: f.write(six.u(json.dumps(config, indent=2))) print("... done")
def write_password_json(user): with open("jupyter-passwords/%s.passwd" % (user,), "r") as f: word = passwd(f.readline().strip()) js = { "NotebookApp": { "password" : word } } with open("jupyter_notebook_configs/%s.json" % (user,), "w") as f2: json.dump(js, f2)