79 lines
2.3 KiB
Python
Executable file
79 lines
2.3 KiB
Python
Executable file
#!/usr/bin/python
|
|
|
|
# A wrapper script over ldapadd
|
|
|
|
from os import remove
|
|
from secrets import token_urlsafe
|
|
from subprocess import run, call, check_output
|
|
from sys import argv
|
|
|
|
|
|
def adduser(username, firstname, lastname, email, pubkey, password):
|
|
"""Add a new user"""
|
|
|
|
# Get UID
|
|
output = check_output(['ldapsearch', '-x', 'uidNumber']).decode('utf-8')
|
|
used = {int(line.split()[1]) for line in output.split('\n') if line.startswith('uid')}
|
|
uid = next(u for u in range(1001, 10000) if u not in used)
|
|
|
|
if firstname == lastname:
|
|
fullname = firstname
|
|
else:
|
|
fullname = f'{firstname} {lastname}'
|
|
|
|
# Generate password hash using OpenSSL
|
|
with open('password', 'w') as f:
|
|
f.write(password)
|
|
hashed_password = check_output(['openssl', 'passwd', '-6', '-in', 'password']).decode('utf-8')[:-1]
|
|
remove('password')
|
|
|
|
# Construct LDIF
|
|
ldif = f'''dn: uid={username},ou=People,dc=exozy,dc=me
|
|
objectClass: top
|
|
objectClass: person
|
|
objectClass: organizationalPerson
|
|
objectClass: inetOrgPerson
|
|
objectClass: posixAccount
|
|
objectClass: shadowAccount
|
|
uid: {username}
|
|
cn: {fullname}
|
|
sn: {lastname}
|
|
givenName: {firstname}
|
|
userPassword: {{CRYPT}}{hashed_password}
|
|
mail: {email}
|
|
loginShell: /bin/fish
|
|
uidNumber: {uid}
|
|
gidNumber: {uid}
|
|
homeDirectory: /home/{username}
|
|
|
|
dn: cn={username},ou=Group,dc=exozy,dc=me
|
|
objectClass: top
|
|
objectClass: posixGroup
|
|
cn: {username}
|
|
gidNumber: {uid}'''
|
|
|
|
# Write to file
|
|
with open('user.ldif', 'w') as f:
|
|
f.write(ldif)
|
|
|
|
# Add user
|
|
ret = call(['ldapadd', '-y', '/etc/ldappass', '-D', 'cn=Manager,dc=exozy,dc=me', '-f', 'user.ldif'])
|
|
if ret != 0:
|
|
return
|
|
remove('user.ldif')
|
|
|
|
# Configure and set up user
|
|
# Make home directory
|
|
run(['mkhomedir_helper', username, '077'])
|
|
run(['sudo', '-u', username, 'mkdir', f'/home/{username}/.ssh'])
|
|
run(['sudo', '-u', username, 'tee', f'/home/{username}/.ssh/authorized_keys'], input=pubkey.encode('utf-8'))
|
|
run(['sudo', '-u', username, 'tee', f'/home/{username}/password'], input=password.encode('utf-8'))
|
|
# Set up Flatpak
|
|
# This is a workaround for the error "flatpak refusing to operate under sudo with --user"
|
|
run(['sudo', '-u', username, 'sh', '-c',
|
|
'flatpak remote-add flathub https://dl.flathub.org/repo/flathub.flatpakrepo --user'])
|
|
|
|
|
|
# Generate temporary password
|
|
adduser(*argv[1:], token_urlsafe(6))
|