Replace shell commands with lists for subprocess run

This commit is contained in:
Anthony Wang 2022-01-05 18:04:23 -06:00
parent 0af014b976
commit 24746ca761
Signed by: a
GPG key ID: BC96B00AEC5F2D76
3 changed files with 80 additions and 97 deletions

162
adduser
View file

@ -1,98 +1,82 @@
#!/usr/bin/python3
import sys
import os
from subprocess import run, check_output
# Determine if running in interactive mode
interactive = len(sys.argv) == 1
# Hash a password for LDAP
# https://github.com/tonyprawiro/cracking-ldap
def ldap_hash(password):
return password
# 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]
# Add a new user
def adduser(username, firstname, lastname, email, password, ldap_pass=None):
# Get UID
output = check_output(['getent', 'passwd'])
uid = [u for u in range(1000, 10000) if str(u) not in output][0]
# Get UID
output = os.popen('getent passwd').read()
uid = [u for u in range(1000, 10000) if str(u) not in output][0]
# 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}
# Password
if interactive:
password = os.popen(
'tr -dc A-Za-z0-9 </dev/urandom | head -c 16; echo ""').read()[:-1]
print('Password:', password)
hashedpassword = os.popen('slappasswd -s "' + password + '"').read()[:-1]
else:
hashedpassword = sys.argv[5]
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=ldap_hash(password))
# Write to file and get confirmation
filename = username + '.ldif'
with open(filename, 'w') as f:
f.write(ldif)
# Add user
if ldap_pass == None:
run(['vim', filename])
confirm = input('OK? (y/N) ')
if confirm != 'y' and confirm != 'Y':
run(['gio', 'trash', filename])
print('Cancelled')
return
ret = call(['ldapadd', '-D', 'cn=Manager,dc=exozy,dc=me', '-W', '-f', filename])
else:
ret = call(['ldapadd', '-D', 'cn=Manager,dc=exozy,dc=me', '-w', ldap_pass, '-f', filename])
if ret != 0:
os.remove(filename)
return
run(['chown', 'ta180m:ta180m', filename])
run(['mv', filename, '/home/ta180m/git/LDAP/users'])
# Configure user
run(['sudo', 'mkhomedir_helper', username, '077'])
run(['sudo', '-u', username, 'mkdir', '/home/' + username + '/.config'])
# Set up Flatpak
run(['sudo', '-u', username, 'flatpak', 'remote-add', '--if-not-exists', 'flathub',
'https://dl.flathub.org/repo/flathub.flatpakrepo', '--user'])
# Set default browser
run(['sudo', '-u', username, 'xdg-settings', 'set', 'default-web-browser', 'firefox.desktop'])
# 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:
ret = os.system('ldapadd -D "cn=Manager,dc=exozy,dc=me" -W -f ' + filename)
else:
ret = os.system('ldapadd -D "cn=Manager,dc=exozy,dc=me" -w "' +
sys.argv[6] + '" -f ' + filename)
if ret != 0:
os.remove(filename)
exit(0)
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') # Set up Flatpak
os.system('sudo -u ' + username +
' xdg-settings set default-web-browser firefox.desktop') # Set default browser
# Running as script
if __name__ == "__main__":
username, firsname, lastname, email, password = [sys.argv[i] for i in range(1, 6)]
adduser(username, firstname, lastname, email, password)

View file

@ -6,10 +6,10 @@ from subprocess import run
# Delete a user
def deluser(username):
# Delete user
run('ldapdelete -W -D "cn=Manager,dc=exozy,dc=me" "uid=' + username +
',ou=People,dc=exozy,dc=me" "cn=' + username + ',ou=Group,dc=exozy,dc=me"', shell=True)
run(['ldapdelete', '-W', '-D', 'cn=Manager,dc=exozy,dc=me', 'uid=' + username +
',ou=People,dc=exozy,dc=me', 'cn=' + username + ',ou=Group,dc=exozy,dc=me'])
# Cleanup
run('sudo rm -rf /home/' + username, shell=True)
run(['sudo', 'rm', '-rf', '/home/' + username])
# Running as script
if __name__ == "__main__":

View file

@ -1,7 +1,6 @@
#!/usr/bin/python
import os
from subprocess import run
from subprocess import run, check_output
from json import loads
from http.server import BaseHTTPRequestHandler, HTTPServer
@ -10,8 +9,7 @@ class Server(BaseHTTPRequestHandler):
def do_POST(self):
content_length = int(self.headers['Content-Length'])
data = loads(self.rfile.read(content_length).decode('utf-8'))
data['password'] = os.popen(
'slappasswd -s "' + data['password'] + '"').read()[:-1]
data['password'] = checkout_output(['slappasswd', '-s', data['password']])
print(data)
if data['code'] != code:
@ -24,7 +22,8 @@ class Server(BaseHTTPRequestHandler):
print('Cannot contain double quotes')
return
run(['/home/ta180m/git/scripts/adduser', data['username'], data['firstname'].capitalize(), data['lastname'].capitalize(), data['email'], data['password'], ldap_pass])
run(['/home/ta180m/git/scripts/adduser', data['username'], data['firstname'].capitalize(),
data['lastname'].capitalize(), data['email'], data['password'], ldap_pass])
self.send_response(200)
self.send_header('Content-type', 'text/html')