Skip to content

Instantly share code, notes, and snippets.

@bryanisimo
Last active May 16, 2018 22:15
Show Gist options
  • Select an option

  • Save bryanisimo/43e9e61377a7774a663bb2a96058042d to your computer and use it in GitHub Desktop.

Select an option

Save bryanisimo/43e9e61377a7774a663bb2a96058042d to your computer and use it in GitHub Desktop.
Creating www-data users in Linux # Python 2.7
import os
import pwd
import subprocess
import argparse
def demote(user_uid, user_gid):
def result():
report_ids('starting demotion')
os.setgid(user_gid)
os.setuid(user_uid)
report_ids('finished demotion')
return result
def report_ids(msg):
print 'uid, gid = %d, %d; %s' % (os.getuid(), os.getgid(), msg)
def exec_command_as(username, command_array):
new_user = pwd.getpwnam(username)
new_user_uid = new_user.pw_uid
new_user_gid = new_user.pw_gid
new_user_name = new_user.pw_name
new_user_home_dir = new_user.pw_dir
env = os.environ.copy()
env['HOME'] = new_user_home_dir
env['LOGNAME'] = new_user_name
env['USER'] = new_user_name
process = subprocess.Popen(
command_array,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
preexec_fn=demote(new_user_uid, new_user_gid),
env=env)
outs, errs = process.communicate()
# result = process.wait()
if process.returncode != 0:
print '----------------------------------[ERROR EXECUTING]:'
print command_array
print 'output:\n', outs
print 'errors:\n', errs
print process
else:
print command_array, ':\n', outs
return process.returncode
def find_line_in_file(file_path, line_str, strict):
file_contents = open(file_path, 'r').read().split('\n')
lines_l = len(file_contents)
if strict:
for lines in range(lines_l, 0, -1):
lines_l = lines_l - 1
if file_contents[lines_l] == line_str:
return lines_l
else:
for lines in range(lines_l, 0, -1):
lines_l = lines_l - 1
if file_contents[lines_l].find(line_str) != -1:
return lines_l
return -1
def add_line_to_file(file_path, line_str, after_str, strict):
if find_line_in_file(file_path, line_str, strict) != -1:
print 'This line is already in the file "' + file_path + '":\n', line_str
return 1
if after_str:
index = find_line_in_file(file_path, after_str, strict)
if index > -1:
file_contents = open(file_path, 'r').read().split('\n')
file_contents.insert(index + 1, line_str)
new_str = '\n'.join(file_contents)
# print new_str
with open(file_path, 'w') as f:
f.write(new_str)
else:
print 'String not found:\n', after_str
return 1
else:
with open(file_path, 'a') as f:
f.write(line_str)
return 0
def create_user(username, name):
# Creating user
if not os.path.isdir('/home/' + username):
print 'Creating ' + name + ' as "' + username + '"'
os.system("sudo adduser --home '/home/" + username + "' --disabled-login --gecos '" + name + "' " + username)
os.system('sudo usermod -g www-data ' + username)
# Default Folder
if not os.path.isdir('/home/' + username + '/projects'):
command_array = ['mkdir', '/home/' + username + '/projects']
exec_command_as(username, command_array)
# Deploy key
private_key_path = '/home/' + username + '/.ssh/id_rsa'
public_key_path = private_key_path + '.pub'
if not os.path.exists(private_key_path):
command_array = [
'ssh-keygen',
'-f', private_key_path,
'-t', 'rsa',
'-b', '4096',
'-q'
]
exec_command_as(username, command_array)
print 'Use the next deploy key:\n\n'
with open(public_key_path, 'r') as f:
print f.read()
print '\n\n'
return 0
def main():
# Getting params from shell
parser = argparse.ArgumentParser()
parser.add_argument('--username', help='This is the username ex: kyo_kusanagi')
parser.add_argument('--name', help='Real name ex: "Kyo Kusanagi"')
parser.add_argument('--sudoer', help='If this is a sudoer user set it as true')
args = parser.parse_args()
username = args.username
name = args.name
if not username:
username = raw_input('Write username:\n')
if not name:
name = raw_input('Write real name:\n')
if username and name:
create_user(username, name)
# Add user to sudoers list
sudoer = False
valid_values = [1, '1', 'true', 'yes', 'y']
if args.sudoer:
if args.sudoer.lower() in valid_values:
sudoer = True
else:
input_sudoer = raw_input('Is this a sudoer user?:\n')
if input_sudoer.lower() in valid_values:
sudoer = True
if sudoer:
line_str = username + ' ALL = (ALL) NOPASSWD: ALL #generated_user'
add_line_to_file('/etc/sudoers',
line_str,
'# User privilege specification',
True)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment