scripts/adduser

106 lines
3 KiB
Python
Executable file

#!/usr/bin/python3
import sys
import os
# Determine if running in interactive mode
interactive = len(sys.argv) == 1
# Get user details
if interactive:
username = input('Enter username: ')
firstname = input('Enter first name: ')
lastname = input('Enter last name: ')
email = input('Enter email: ')
else:
username = sys.argv[1]
firstname = sys.argv[2]
lastname = sys.argv[3]
email = sys.argv[4]
# Get UID
if interactive:
custom_uid = input('Would you like to enter a custom UID? (y/N) ')
else:
custom_uid = 'n'
if custom_uid == 'y' or custom_uid == 'Y':
uid = input('Enter UID: ')
else:
uid = 1001 + len([file for file in os.listdir('.') if file.endswith('.ldif')])
# Password
if interactive:
password = os.popen('tr -dc A-Za-z0-9 </dev/urandom | head -c 16; echo ""').read()[:-1]
print('Password:', password)
else:
password = sys.argv[5]
hashedpassword = os.popen('slappasswd -s ' + password).read()[:-1]
# Construct LDIF
ldif = '''dn: uid={username},ou=People,dc=exozy,dc=me
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetOrgPerson
objectClass: posixAccount
objectClass: shadowAccount
uid: {username}
cn: {firstname} {lastname}
sn: {lastname}
givenName: {firstname}
userPassword: {hashedpassword}
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}'''.format(username=username,
firstname=firstname,
lastname=lastname,
email=email,
uid=uid,
hashedpassword=hashedpassword)
# Write to file and get confirmation
filename = username + '.ldif'
with open(filename, 'w') as f:
f.write(ldif)
if interactive:
os.system('vim ' + filename)
confirm = input('OK? (y/N) ')
if confirm != 'y' and confirm != 'Y':
os.system('gio trash ' + filename)
print('Cancelled')
exit(0)
# Add user
if interactive:
os.system('ldapadd -D "cn=Manager,dc=exozy,dc=me" -W -f ' + filename)
else:
os.system('ldapadd -D "cn=Manager,dc=exozy,dc=me" -w "' + sys.argv[6] + '" -f ' + filename)
os.system('chown ta180m:ta180m ' + filename)
os.system('mv ' + filename + ' /home/ta180m/git/LDAP/Users')
# Configure user
os.system('sudo mkhomedir_helper ' + username + ' 077')
os.system('sudo -u ' + username + ' mkdir /home/' + username + '/.config')
os.system('sudo -u ' + username + ' flatpak remote-add --if-not-exists flathub https://dl.flathub.org/repo/flathub.flatpakrepo --user')
os.system('sudo -u ' + username + ' xdg-settings set default-web-browser firefox.desktop')
# Set up rootless Podman
# https://wiki.archlinux.org/title/Podman#Set_subuid_and_subgid
start = str((int(uid) - 999) * 100000)
end = str(int(start) + 65535) # Allocate 65536 UIDs
os.system('sudo usermod --add-subuids ' + start + '-' + end + ' --add-subgids ' + start + '-' + end + ' ' + username)