Last active
February 26, 2020 16:17
-
-
Save pcyin/7f9e5785f6852a3d5b5132761c7f127f to your computer and use it in GitHub Desktop.
A python script to add new user with SSH key-based authentication
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import sys | |
assert sys.version_info > (3, 0), 'This script only supprts Python 3+' | |
from pathlib import Path | |
try: | |
import sh | |
from sh import adduser, mkdir, cat, chown, chmod | |
except: | |
print('This script requires the `sh` library. Please install via `pip install sh`') | |
exit(1) | |
if len(sys.argv) != 4: | |
print('Usage: sudo env "PATH=$PATH" python script.py USER_NAME FULL_NAME PUBLIC_KEY') | |
exit(1) | |
user_name=sys.argv[1] | |
full_name=sys.argv[2] | |
public_key=sys.argv[3] | |
adduser('--disabled-password', '--gecos', f'"{full_name}"', user_name) | |
ssh_folder = Path(f'/home/{user_name}/.ssh') | |
ssh_folder.mkdir(parents=True, exist_ok=True) | |
with (ssh_folder / 'authorized_keys').open('w') as f: | |
f.write(public_key) | |
chown('-R', f'{user_name}:{user_name}', str(ssh_folder)) | |
chmod('0700', str(ssh_folder)) | |
chmod('0600', str(ssh_folder / 'authorized_keys')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment