Files
ssh/docker/ssh-server/app/users.py
Márcio Fernandes f6e6d4dba9
Some checks failed
/ build-docker-image (push) Failing after 23s
ssh server alpha
2025-09-06 23:32:31 +00:00

90 lines
2.4 KiB
Python

import yaml
import subprocess
import crypt
import os
import globals
import pwd
# users:
# - username: alice
# authorized_keys: publich ssh key
# - username: bob
# password: hunter2
def user_exists(username):
try:
pwd.getpwnam(username)
return True
except KeyError:
return False
def create_user(uid, username ,password, shell="/bin/bash"):
if not shell: shell = "/bin/bash"
if not username:
return
useradd_cmd = [
'useradd',
'-m',
'-s', shell,
]
if uid: useradd_cmd.append("-u " + str(uid))
if password: useradd_cmd.append("-p" + crypt.crypt(password, crypt.mksalt(crypt.METHOD_SHA512)))
useradd_cmd.append(username)
try:
subprocess.run(useradd_cmd
, check=True)
print(f"✅ User '{username}' created with shell '{shell}' and password.")
except subprocess.CalledProcessError as e:
print(f"❌ Failed to create user '{username}': {e}")
def setup_ssh(username, public_key):
ssh_dir = f"/home/{username}/.ssh"
auth_keys = os.path.join(ssh_dir, "authorized_keys")
uid = pwd.getpwnam(username).pw_uid
gid = pwd.getpwnam(username).pw_gid
os.makedirs(ssh_dir, mode=0o700, exist_ok=True)
# Check if key already exists
key_exists = False
if os.path.exists(auth_keys):
with open(auth_keys, "r") as f:
existing_keys = f.read().splitlines()
key_exists = public_key.strip() in existing_keys
if not key_exists:
with open(auth_keys, "a") as f:
f.write(public_key.strip() + "\n")
print(f"🔐 SSH key added for '{username}'.")
else:
print(f"⚠️ SSH key already exists for '{username}'. Skipping.")
os.chmod(ssh_dir, 0o700)
os.chmod(auth_keys, 0o600)
os.chown(ssh_dir, uid, gid)
os.chown(auth_keys, uid, gid)
def load():
users = globals.get_config()["users"] if globals.config_exits() else None
if users:
for user in users:
if not user_exists(user.get('username')):
create_user(user.get('uid'), user.get('username'),user.get('password'), user.get('shell'))
if user.get('public_keys'):
for public_key in user.get('public_keys'):
setup_ssh(user.get('username'), public_key)
if __name__ == "__main__":
globals.load_config()
load()