add new task set_file_ssh_authorized_keys

This commit is contained in:
Jan Dittberner 2015-01-29 22:23:11 +01:00
parent 4e144fb49d
commit 307ccf4307
3 changed files with 67 additions and 0 deletions

View file

@ -1,6 +1,8 @@
Changelog
=========
* :feature:`-` add new task set_file_ssh_authorized_keys to add SSH keys for
users
* :support:`-` improved logging in fileservertasks.tasks, got rid of
GVAFileException

View file

@ -8,6 +8,7 @@ from __future__ import absolute_import, unicode_literals
import os
import subprocess
from tempfile import mkstemp
from gvafile import settings
@ -37,6 +38,19 @@ def log_and_raise(exception, message, *args):
raise Exception(message % args)
def _build_authorized_keys_path(username):
"""
Constructs the file path for the authorized_keys file for a given username.
:param str username: the user name
:return: the file name
:rtype: str
"""
return os.path.join(
settings.GVAFILE_SFTP_AUTHKEYS_DIRECTORY, username, 'keys')
def _build_sftp_directory_name(username):
"""
Constructs the SFTP directory name for a given username.
@ -287,3 +301,52 @@ def delete_file_website_hierarchy(username, sitename):
_LOGGER.info(
'deleted website directory %s of user %s', website_directory, username)
return website_directory
@shared_task
def set_file_ssh_authorized_keys(username, ssh_keys):
"""
This task sets the authorized keys for ssh logins.
:param str username: the user name
:param list ssh_key: an ssh_key
:raises Exception: if the update of the creation or update of ssh
authorized_keys failed
:return: the name of the authorized_keys file
:rtype: str
"""
ssh_authorized_keys_file = _build_authorized_keys_path(username)
if ssh_keys:
try:
authkeystemp, filename = mkstemp()
conffile = os.fdopen(authkeystemp, 'w')
conffile.write("\n".join(ssh_keys))
finally:
if conffile:
conffile.close()
try:
subprocess.check_output([
SUDO_CMD, INSTALL_CMD, '-o', username, '-g', username,
'm', '0500', '-d', os.path.dirname(ssh_authorized_keys_file)],
stderr=subprocess.STDOUT)
subprocess.check_output([
SUDO_CMD, INSTALL_CMD, '-o', username, '-g', username,
'-m', '0400', filename, ssh_authorized_keys_file],
stderr=subprocess.STDOUT)
subprocess.check_output([
SUDO_CMD, RM_CMD, filename], stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as cpe:
log_and_raise(
cpe, 'could not write authorized_keys file for user %s',
username)
else:
try:
subprocess.check_output([
SUDO_CMD, RM_CMD, '-rf',
os.path.dirname(ssh_authorized_keys_file)],
stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as cpe:
log_and_raise(
cpe, 'could not remove the authorized_keys file of user %s',
username)

View file

@ -42,4 +42,6 @@ BROKER_URL = get_env_setting('GVAFILE_BROKER_URL')
########## GVAFILE CONFIGURATION
GVAFILE_SFTP_DIRECTORY = get_env_setting('GVAFILE_SFTP_DIRECTORY')
GVAFILE_MAIL_DIRECTORY = get_env_setting('GVAFILE_MAIL_DIRECTORY')
GVAFILE_SFTP_AUTHKEYS_DIRECTORY = get_env_setting(
'GVAFILE_SFTP_AUTHKEYS_DIRECTORY')
########## END GVAFILE CONFIGURATION