dynamically get home directory by logon user

This commit is contained in:
Tuncay ÇOLAK 2020-09-10 14:20:00 +03:00
parent c07815a723
commit a26cf032a8
6 changed files with 114 additions and 124 deletions

View file

@ -41,78 +41,65 @@ class DefaultPolicy:
self.logger.error('Firefox installation path not found')
self.logger.info("if mozilla profile is not created run firefox to create profile for user: " + username)
if not Util.is_exist("/home/" + username + "/.mozilla/"):
homedir = self.util.get_homedir(username)
self.logger.info("Get home directory is {0} of {1} for firefox default policy".format(homedir, username))
if not Util.is_exist("{0}/.mozilla/".format(homedir)):
self.logger.info("firefox profile does not exist. Check autostart file.")
if not Util.is_exist("/home/" + username + "/.config/autostart/"):
if not Util.is_exist("{0}/.config/autostart/".format(homedir)):
self.logger.info(".config/autostart folder does not exist. Creating folder.")
Util.create_directory("/home/" + username + "/.config/autostart/")
Util.create_directory("{0}/.config/autostart/".format(homedir))
else:
self.logger.info(".config/autostart folder exists.")
self.logger.info(
"Checking if {0}-autostart-for-profile.desktop autorun file exists.".format(exec_command))
self.logger.info("Checking if {0}-autostart-for-profile.desktop autorun file exists.".format(exec_command))
if not Util.is_exist(
"/home/" + username + "/.config/autostart/{0}-autostart-for-profile.desktop".format(exec_command)):
self.logger.info(
"{0}-autostart-for-profile.desktop autorun file does not exists. Creating file.".format(
exec_command))
Util.create_file(
"/home/" + username + "/.config/autostart/{0}-autostart-for-profile.desktop".format(exec_command))
if not Util.is_exist("{0}/.config/autostart/{1}-autostart-for-profile.desktop".format(homedir, exec_command)):
self.logger.info("{0}-autostart-for-profile.desktop autorun file does not exists. Creating file.".format(exec_command))
Util.create_file("{0}/.config/autostart/{1}-autostart-for-profile.desktop".format(homedir, exec_command))
content = "[Desktop Entry]\n\n" \
"Type=Application\n\n" \
"Exec={0}{1} www.liderahenk.org".format(firefox_path, exec_command)
Util.write_file(
"/home/" + username + "/.config/autostart/{0}-autostart-for-profile.desktop".format(exec_command),
content)
self.logger.info(
"Autorun config is written to {0}-autostart-for-profile.desktop.".format(exec_command))
Util.write_file("{0}/.config/autostart/{1}-autostart-for-profile.desktop".format(homedir, exec_command), content)
self.logger.info("Autorun config is written to {0}-autostart-for-profile.desktop.".format(exec_command))
else:
self.logger.info("{0}-autostart-for-profile.desktop exists".format(exec_command))
else:
self.logger.info(".mozilla firefox profile path exists. Delete autorun file.")
Util.delete_file(
"/home/" + username + "/.config/autostart/{0}-autostart-for-profile.desktop".format(exec_command))
Util.delete_file("{0}/.config/autostart/{1}-autostart-for-profile.desktop".format(homedir, exec_command))
## disabled update package notify for user
def disable_update_package_notify(self, username):
homedir = self.util.get_homedir(username)
self.logger.info("Get home directory is {0} of {1} for disable update package notify".format(homedir, username))
xfce4_notify_template_path = "/usr/share/ahenk/base/default_policy/config-files/xfce4-notifyd.xml"
fileName = "/home/{0}/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-notifyd.xml".format(username)
fileName = "{0}/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-notifyd.xml".format(homedir)
if not self.util.is_exist(fileName):
## if configuration file does not exist will be create /home/{username}/.config/xfce4/xfconf/xfce-perchannel-xml/
self.logger.info("Configuration file does not exist")
self.util.create_directory("/home/{0}/.config/xfce4/xfconf/xfce-perchannel-xml/".format(username))
self.logger.info("Created directory /home/{0}/.config/xfce4/xfconf/xfce-perchannel-xml/".format(username))
self.util.copy_file(xfce4_notify_template_path, "/home/{0}/.config/xfce4/xfconf/xfce-perchannel-xml/".format(username))
self.util.create_directory("{0}/.config/xfce4/xfconf/xfce-perchannel-xml/".format(homedir))
self.logger.info("Created directory {0}/.config/xfce4/xfconf/xfce-perchannel-xml/".format(homedir))
self.util.copy_file(xfce4_notify_template_path, "{0}/.config/xfce4/xfconf/xfce-perchannel-xml/".format(homedir))
self.logger.info("Copy xfce4-notifyd.xml template file")
gid = self.util.file_group("/home/{0}".format(username))
cmd = "chown -R {0}:{1} /home/{0}/.config".format(username, gid)
gid = self.util.file_group(homedir)
cmd = "chown -R {0}:{1} {2}/.config".format(username, gid, homedir)
self.util.execute(cmd)
self.logger.info("Set permissons for /home/{0}.config directory".format(username))
self.notifyd_xml_parser(username)
self.logger.info("Set permissons for {0}/.config directory".format(homedir))
self.notifyd_xml_parser(username, homedir)
else:
self.logger.info("Configuration file exist")
self.notifyd_xml_parser(username)
self.notifyd_xml_parser(username, homedir)
pk_update_icon_file = "/etc/xdg/autostart/pk-update-icon.desktop"
if self.util.is_exist(pk_update_icon_file):
self.logger.info("{0} file exists".format(pk_update_icon_file))
self.util.rename_file(pk_update_icon_file, pk_update_icon_file+".ahenk")
self.logger.info("Renamed from {0} to {0}.ahenk".format(pk_update_icon_file))
self.logger.info("Disabled autostart for pk-update-icon")
else:
self.logger.info("File not found")
self.logger.info("Disable notifications if there is a package update notification for user: " + username)
def notifyd_xml_parser(self, username):
fileName = "/home/{0}/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-notifyd.xml".format(username)
def notifyd_xml_parser(self, username, homedir):
fileName = "{0}/.config/xfce4/xfconf/xfce-perchannel-xml/xfce4-notifyd.xml".format(homedir)
tree = ET.parse(fileName)
root = tree.getroot()
app_name_for_blocking = "pk-update-icon"
@ -144,4 +131,4 @@ class DefaultPolicy:
new_element.attrib["value"] = app_name_for_blocking
tree.write(fileName)
else:
self.logger.info("'" + app_name_for_blocking + "' is already added to muted_applications tag.")
self.logger.info("'" + app_name_for_blocking + "' is already added to muted_applications tag.")

View file

@ -14,6 +14,7 @@ import subprocess
import uuid
import locale
from base.scope import Scope
from os.path import expanduser
class Util:
@ -450,8 +451,12 @@ class Util:
result_code, p_out, p_err = Util.execute("ls {}".format(xfce4_session))
if result_code == 0:
desktop_env = "xfce"
return desktop_env
# return home directory for user. "/home/username"
@staticmethod
def get_homedir(user):
try:
return expanduser("~{0}".format(user))
except:
raise

View file

@ -131,7 +131,10 @@ class Browser(AbstractPlugin):
def find_user_preference_paths(self, user_name):
paths = []
firefox_path = '/home/' + user_name + '/.mozilla/firefox/'
homedir = self.get_homedir(user_name)
self.logger.info("Get home directory is {0} of {1} for firefox policy".format(homedir, user_name))
firefox_path = '{0}/.mozilla/firefox/'.format(homedir)
self.logger.info("Firefox path is {0}".format(firefox_path))
if self.is_exist(firefox_path + 'profiles.ini'):
profile_ini_file = open(firefox_path + 'profiles.ini', 'r')
profile_ini_file_lines = profile_ini_file.readlines()

View file

@ -20,6 +20,7 @@ class Conky(AbstractPlugin):
self.autostart_dir_path = '{0}.config/autostart/'
self.autorun_file_path = '{0}conky.desktop'
self.logger.debug('Parameters were initialized.')
self.homedir = None
def handle_policy(self):
try:
@ -36,7 +37,9 @@ class Conky(AbstractPlugin):
if 'username' in self.context.data and self.context.get('username') is not None:
self.logger.debug('This is user profile, parameters reinitializing.')
self.username = self.context.get('username')
self.conky_config_file_dir = '{0}.conky/'.format(self.Sessions.user_home_path(self.username))
self.homedir = self.get_homedir(self.username) + '/'
self.logger.info("Get home directory of {0}".format(self.homedir))
self.conky_config_file_dir = '{0}.conky/'.format(self.homedir)
self.conky_config_file_path = '{0}conky.conf'.format(self.conky_config_file_dir)
self.machine_profile = False
@ -110,15 +113,14 @@ class Conky(AbstractPlugin):
if self.Sessions.user_name() is not None and len(self.Sessions.user_name()) > 0:
for username in self.Sessions.user_name():
self.logger.debug('Removing conf file of user {0}'.format(username))
self.delete_file(self.autorun_file_path.format( self.autostart_dir_path.format(self.Sessions.user_home_path(username))))
self.delete_file(self.autorun_file_path.format( self.autostart_dir_path.format(self.homedir)))
else:
self.logger.debug('There are no user')
else:
home_path = self.Sessions.user_home_path(self.username)
self.logger.debug('Creating autorun file for user {0}'.format(self.username))
self.create_autorun_file(self.autostart_dir_path.format(home_path),
self.create_autorun_file(self.autostart_dir_path.format(self.homedir),
self.conky_config_file_path,
self.autorun_file_path.format(self.autostart_dir_path.format(home_path)))
self.autorun_file_path.format(self.autostart_dir_path.format(self.homedir)))
self.logger.debug('Autorun created')
def create_autorun_file(self, autostart_path, conky_config_file_path, autorun_file_path):

View file

@ -17,7 +17,8 @@ class Safe(AbstractPlugin):
self.logger.debug('Conky named processes will be killed.')
self.execute('killall -9 conky')
# delete autostart and conky config file of logout username
self.conky_config_file_dir = '{0}.conky/'.format(self.Sessions.user_home_path(self.username))
self.homedir = self.get_homedir(self.username) + '/'
self.conky_config_file_dir = '{0}.conky/'.format(self.homedir)
self.conky_config_file_path = '{0}conky.conf'.format(self.conky_config_file_dir)
if self.is_exist(self.conky_config_file_dir):
self.logger.debug('Conky config file will be deleted of {0}.'.format(self.username))
@ -25,8 +26,7 @@ class Safe(AbstractPlugin):
self.autostart_dir_path = '{0}.config/autostart/'
self.autorun_file_path = '{0}conky.desktop'
home_path = self.Sessions.user_home_path(self.username)
auto_start_file = self.autorun_file_path.format(self.autostart_dir_path.format(home_path))
auto_start_file = self.autorun_file_path.format(self.autostart_dir_path.format(self.homedir))
if self.is_exist(auto_start_file):
self.delete_file(auto_start_file)
self.logger.debug('Removing autostart file of user {0}'.format(self.username))

View file

@ -5,10 +5,8 @@ import json
import time
from base64 import b64encode
from os import urandom
from base.plugin.abstract_plugin import AbstractPlugin
class SetupVnc(AbstractPlugin):
"""docstring for SetupVnc"""
@ -21,7 +19,6 @@ class SetupVnc(AbstractPlugin):
self.port = self.get_port_number()
self.logger.debug('Parameters were initialized')
def handle_task(self):
self.logger.debug('Handling task')
try:
@ -33,7 +30,6 @@ class SetupVnc(AbstractPlugin):
self.data['password'] = self.password
self.data['host'] = ip_addresses
self.logger.debug('Response data created')
if self.data['permission'] == "yes":
message = "VNC başarılı bir şekilde yapılandırıldı!\n{0} ip'li bilgisayara uzak erişim sağlanacaktır.\nKullanıcısının izni için lütfen bekleyiniz...'".format(self.data['host'])
elif self.data['permission'] == "no":
@ -52,83 +48,83 @@ class SetupVnc(AbstractPlugin):
message='VNC sunucusu çalışırken bir hata oluştu.')
def run_vnc_server(self):
user_name = self.db_service.select_one_result('session', 'username', " 1=1 order by id desc ")
self.logger.info('get logon username is {0}'.format(user_name))
self.logger.debug('Is VNC server installed?')
if self.is_installed('x11vnc') is False:
self.logger.debug('VNC server not found, it is installing')
self.install_with_apt_get('x11vnc')
users = self.Sessions.user_name()
self.logger.debug('[XMessage] users : ' + str(users))
self.logger.debug('VNC server was installed')
self.logger.debug('Killing running VNC proceses')
self.execute("ps aux | grep x11vnc | grep 'port " + self.port + "' | awk '{print $2}' | xargs kill -9",
result=False)
self.logger.debug('Running VNC proceses were killed')
self.logger.debug('Getting display and username...')
display_number = self.get_username_display(user_name)
# if len(arr) < 1:
# raise NameError('Display not found!')
for user in users:
user_display = self.Sessions.display(user)
# params = str(arr[0]).split(' ')
homedir = self.get_homedir(user_name)
self.logger.info("Get home directory of {0} is {1}".format(user_name, homedir))
# self.logger.info("--------->>>> " + str(params))
self.logger.debug('Username:{0} Display:{1}'.format(user_name, display_number))
if self.is_exist('{0}/.vncahenk{1}'.format(homedir, user_name)) is True:
self.delete_folder('{0}/.vncahenk{1}'.format(homedir, user_name))
self.logger.debug('Cleaning previous configurations.')
self.logger.debug('Creating user VNC conf file as user')
self.execute('su - {0} -c "mkdir -p {1}/.vncahenk{0}"'.format(user_name, homedir), result=False)
self.logger.debug('Creating password as user')
self.execute('su - {0} -c "x11vnc -storepasswd {1} {2}/.vncahenk{3}/x11vncpasswd"'.format(user_name, self.password, homedir,
user_name), result=False)
self.logger.debug('Running VNC server as user.')
if self.data['permission'] == "yes":
self.send_notify("Liderahenk",
"Lider Ahenk Sistem Yoneticisi tarafindan\n5 sn sonra bilgisayarınıza uzak erişim sağlanacaktır.\nBağlantı kapatıldıktan sonra ayrıca bilgilendirilecektir.",
":0", user_name, timeout=50000)
time.sleep(5)
self.execute('su - {0} -c "x11vnc -accept \'popup\' -gone \'popup\' -rfbport {1} -rfbauth {2}/.vncahenk{0}/x11vncpasswd -o {2}/.vncahenk{3}/vnc.log -display :{4}"'.format(
user_name, self.port, homedir, user_name, display_number), result=False)
elif self.data["permission"] == "no":
self.logger.info("Lider Ahenk sistem yöneticisi 5 sn sonra bilgisayarınıza uzak erişim sağlayacaktır. ")
self.send_notify("Liderahenk",
"Lider Ahenk Sistem Yoneticisi tarafindan\n5 sn sonra bilgisayarınıza uzak erişim sağlanacaktır.\nBağlantı kapatıldıktan sonra ayrıca bilgilendirilecektir.",
":0", user_name, timeout=50000)
time.sleep(5)
self.execute('su - {0} -c "x11vnc -gone \'popup\' -rfbport {1} -rfbauth {2}/.vncahenk{0}/x11vncpasswd -o {2}/.vncahenk{3}/vnc.log -display :{4}"'.format(
user_name, self.port, homedir, user_name, display_number), result=False)
else:
self.execute('su - {0} -c "x11vnc -rfbport {1} -rfbauth {2}/.vncahenk{0}/x11vncpasswd -o {2}/.vncahenk{3}/vnc.log -display :{4}"'.format(
user_name, self.port, homedir, user_name, display_number), result=False)
self.logger.info("Lider Ahenk sistem yöneticisi tarafından kullanıcı izni ve bildirim gerektirmeksizin uzak erişim sağlanmıştır")
self.logger.debug('Is VNC server installed?')
def get_username_display(self, user):
# result_code, p_out, p_err = self.execute("who | awk '{print $1, $5}' | sed 's/(://' | sed 's/)//'", result=True)
# self.logger.debug('Getting display result code:{0}'.format(str(result_code)))
#
# result = []
# lines = str(p_out).split('\n')
# for line in lines:
# arr = line.split(' ')
# if len(arr) > 1 and str(arr[1]).isnumeric() is True:
# result.append(line)
# return result
if self.is_installed('x11vnc') is False:
self.logger.debug('VNC server not found, it is installing')
self.install_with_apt_get('x11vnc')
self.logger.debug('VNC server was installed')
self.logger.debug('Killing running VNC proceses')
self.execute("ps aux | grep x11vnc | grep 'port " + self.port + "' | awk '{print $2}' | xargs kill -9",
result=False)
self.logger.debug('Running VNC proceses were killed')
self.logger.debug('Getting display and username...')
arr = self.get_username_display()
if len(arr) < 1:
raise NameError('Display not found!')
params = str(arr[0]).split(' ')
self.logger.info("--------->>>> "+str(params))
self.logger.debug('Username:{0} Display:{1}'.format(params[0], params[1]))
if self.is_exist('/home/{0}/.vncahenk{0}'.format(params[0])) is True:
self.logger.debug('Cleaning previous configurations.')
# self.delete_folder('/home/{0}/.vncahenk{0}'.format(params[0]))
self.logger.debug('Creating user VNC conf file as user')
self.execute('su - {0} -c "mkdir -p /home/{0}/.vncahenk{1}"'.format(params[0], params[0]), result=False)
self.logger.debug('Creating password as user')
self.execute('su - {0} -c "x11vnc -storepasswd {1} /home/{0}/.vncahenk{2}/x11vncpasswd"'.format(params[0], self.password, params[0]), result=False)
self.logger.debug('Running VNC server as user.')
if self.data['permission'] == "yes":
self.send_notify("Liderahenk", "Lider Ahenk Sistem Yoneticisi tarafindan\n5 sn sonra bilgisayarınıza uzak erişim sağlanacaktır.\nBağlantı kapatıldıktan sonra ayrıca bilgilendirilecektir.",":0", params[0], timeout=50000)
time.sleep(5)
self.execute('su - {0} -c "x11vnc -accept \'popup\' -gone \'popup\' -rfbport {1} -rfbauth /home/{0}/.vncahenk{2}/x11vncpasswd -o /home/{0}/.vncahenk{3}/vnc.log -display :{4}"'.format(
params[0], self.port, params[0], params[0], params[1]), result=False)
elif self.data["permission"] == "no":
self.logger.info("Lider Ahenk sistem yöneticisi 5 sn sonra bilgisayarınıza uzak erişim sağlayacaktır. ")
self.send_notify("Liderahenk", "Lider Ahenk Sistem Yoneticisi tarafindan\n5 sn sonra bilgisayarınıza uzak erişim sağlanacaktır.\nBağlantı kapatıldıktan sonra ayrıca bilgilendirilecektir.", ":0", params[0], timeout=50000)
time.sleep(5)
self.execute('su - {0} -c "x11vnc -gone \'popup\' -rfbport {1} -rfbauth /home/{0}/.vncahenk{2}/x11vncpasswd -o /home/{0}/.vncahenk{3}/vnc.log -display :{4}"'.format(
params[0], self.port, params[0], params[0], params[1]), result=False)
else:
self.execute(
'su - {0} -c "x11vnc -rfbport {1} -rfbauth /home/{0}/.vncahenk{2}/x11vncpasswd -o /home/{0}/.vncahenk{3}/vnc.log -display :{4}"'.format(
params[0], self.port, params[0], params[0], params[1]), result=False)
self.logger.info("Lider Ahenk sistem yöneticisi tarafından kullanıcı izni ve bildirim gerektirmeksizin uzak erişim sağlanmıştır")
def get_username_display(self):
result_code, p_out, p_err = self.execute("who | awk '{print $1, $5}' | sed 's/(://' | sed 's/)//'", result=True)
self.logger.debug('Getting display result code:{0}'.format(str(result_code)))
display_number = None
result = []
lines = str(p_out).split('\n')
for line in lines:
arr = line.split(' ')
if len(arr) > 1 and str(arr[1]).isnumeric() is True:
result.append(line)
return result
for res in result:
arr = res.split(" ")
username = arr[0]
if username == user:
display_number = arr[1]
return display_number
def create_password(self, pass_range):
self.logger.debug('Password created')
@ -139,9 +135,6 @@ class SetupVnc(AbstractPlugin):
self.logger.debug('Target port is 5999')
return '5999'
def handle_task(task, context):
vnc = SetupVnc(task, context)
vnc.handle_task()