You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
jupyterpi/make_user_accounts.py

67 lines
2.5 KiB
Python

#!/usr/bin/env python3
import argparse
import os, sys
from IPython.lib import passwd
from jinja2 import Environment, FileSystemLoader
from random import shuffle
from csv import writer
ap = argparse.ArgumentParser("Create user accounts + jupyterlab settings")
ap.add_argument("--from-file", type=argparse.FileType("r"), default=None, required=True)
ap.add_argument("--passwords", type=argparse.FileType("r"), default="words")
ap.add_argument("--templates", default="make_user_accounts")
ap.add_argument("--csv", type=argparse.FileType("w"), default="users.csv")
ap.add_argument("--nginx", type=argparse.FileType("w"), default="users.nginx.conf")
ap.add_argument("--md", type=argparse.FileType("w"), default="users.md")
ap.add_argument("--port", type=int, default=9060)
ap.add_argument("--addusers", action="store_true", default=False)
args = ap.parse_args()
passwords = args.passwords.read().strip().splitlines()
passwords = [w.lower() for w in passwords]
template_env = Environment(loader=FileSystemLoader(args.templates))
curport = args.port
usernames = args.from_file.read().strip().splitlines()
nbconfig = template_env.get_template("jupyter_notebook_config.py")
csvout = writer(args.csv)
csvout.writerow("username port password".split())
users = []
for username in usernames:
shuffle(passwords)
password = "".join(passwords[:3])
userdata = {}
userdata['username'] = username
userdata['password'] = password
userdata['password_sha1'] = passwd(password)
userdata['port'] = curport
users.append(userdata)
csvout.writerow((userdata['username'], userdata['port'], userdata['password']))
curport += 1
if args.addusers:
os.system(f"sudo adduser {username} --disabled-password --gecos ''")
os.system(f"sudo mkdir /home/{username}/.jupyter")
if os.path.exists(f"/home/{username}/.jupyter/"):
with open("jupyter_notebook_config.temp.py", "w") as f:
print (nbconfig.render(**userdata), file=f)
os.system(f"sudo mv jupyter_notebook_config.temp.py /home/{username}/.jupyter/jupyter_notebook_config.py")
os.system(f"sudo chown -R {username}:{username} /home/{username}/.jupyter")
else:
print (nbconfig.render(**userdata))
print()
if args.addusers:
os.system(f"sudo systemctl enable jupyterlab@{username}")
os.system(f"sudo systemctl start jupyterlab@{username}")
os.system(f"sudo ln -s /var/www /home/{username}/shared")
os.system(f"sudo adduser {username} users")
nginx = template_env.get_template("users.nginx.conf")
print (nginx.render({'users': users}), file=args.nginx)
md = template_env.get_template("users.md")
print (md.render({'users': users}), file=args.md)