You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
calculate-utils-3-unix/pym/unix/variables/unix.py

1200 lines
34 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

# -*- coding: utf-8 -*-
# Copyright 2016 Mir Calculate. http://www.calculate-linux.org
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
from os import path
from calculate.lib.cl_ldap import LDAPConnectError
from calculate.lib.datavars import (ReadonlyVariable, Variable,
VariableError, PasswordError)
from calculate.ldap.variables.helpers import (HashHelper, RandomPasswordHelper,
ServerEnvHelper, LdapSearchHelper,
LdapMaxHelper)
from calculate.unix.variables.helpers import (UnixUserHelper, UnixGroupHelper,
ExistsUserHelper,
ShowFieldsHelper,
FieldsHelper, UnixActionHelper)
from .action import Actions
_ = lambda x: x
from calculate.lib.cl_lang import (setLocalTranslate, getLazyLocalTranslate)
setLocalTranslate('cl_unix3', sys.modules[__name__])
__ = getLazyLocalTranslate(_)
class VariableLdUnixLogin(ReadonlyVariable):
"""
Имя администратор Unix сервера
"""
value = "Unix"
# class VariableLdUnixDn(ServerEnvHelper, ReadonlyVariable):
# """
# DN настроенного сервиса
# """
# fallback_variable = "unix.ld_unix_dn"
# service = "unix"
# parameter = "dn"
class VariableLdUnixDn(ReadonlyVariable):
"""
DN сервиса
"""
value_format = "ou={ld_unix_login},{ldap.ld_services_dn}"
class VariableLdUnixUsersDn(ReadonlyVariable):
"""
DN пользователей сервиса
"""
value_format = "ou=Users,{ld_unix_dn}"
class VariableLdUnixGroupsDn(ReadonlyVariable):
"""
DN групп сервиса
"""
value_format = "ou=Groups,{ld_unix_dn}"
class VariableLdUnixHash(HashHelper, ReadonlyVariable):
"""
Хэш рут пароля
"""
source = "ld_unix_pw"
class VariableLdUnixPw(ServerEnvHelper, RandomPasswordHelper, Variable):
"""
Пароль root
"""
password_len = 9
service = "unix"
parameter = "pass"
@property
def fallback_value(self):
return "test22"
return RandomPasswordHelper.get(self)
class VariableUrUnixLogin(UnixUserHelper, UnixActionHelper, Variable):
"""
Логин настраиваемого пользователя
"""
untrusted = True
opt = ("ur_unix_login",)
metavalue = "USER"
def init(self):
self.label = _("Login")
self.help = _("set user login")
def get_new(self):
return ""
def get_exists(self):
return self.Get('ur_unix_login_exists')
def check_new(self, value):
if not value:
raise VariableError(_("You should specify login"))
if self.search_ldap_user_name(value):
raise VariableError(_("User %s already exists" % value))
if self.search_system_user_name(value):
raise VariableError(
_("User %s already exists in /etc/passwd") % value)
class VariableUrUnixLoginExists(UnixUserHelper, UnixActionHelper, Variable):
"""
Логин настраиваемого пользователя
"""
type = "choice"
opt = ("ur_unix_login_exists",)
metavalue = "USER"
untrusted = True
guitype = "readonly"
def init(self):
self.label = _("Login")
self.help = _("set user login")
def get_new(self):
return ""
def get_exists(self):
return ""
def choice_exists(self):
return ((user.username,
"%s (%s)" % (user.username, user.comment))
for user in self.iterate_ldap_user("uid=*"))
def raiseWrongChoice(self, name, choiceVal, value, error):
if not value:
raise VariableError(_("Please specify user login"))
else:
raise VariableError(_("%s user not found") % value)
class VariableUrUnixGroupName(LdapSearchHelper, UnixActionHelper, Variable):
"""
Логин настраиваемого пользователя
"""
base_dn = "{ld_unix_groups_dn}"
search_filter = '(cn={value})'
untrusted = True
opt = ("ur_unix_group_name",)
metavalue = "GROUP"
def init(self):
self.label = _("Group")
self.help = _("set the group name")
def get_new(self):
return ""
def get_exists(self):
return self.Get('ur_unix_group_name_exists')
def check(self, value):
if not value:
raise VariableError(_("You should specify group name"))
if self.check_name(value):
raise VariableError(_("Group name already exists"))
class VariableUrUnixGroupLabel(ReadonlyVariable):
"""
Информационное поле для закладки
"""
type = "label"
def init(self):
self.label = _("Group")
def get(self):
return self.Get('ur_unix_group_name')
def uncompatible(self):
return self.label
class VariableUrUnixGroupNameExists(UnixUserHelper, UnixGroupHelper, Variable):
"""
Логин настраиваемого пользователя
"""
type = "choice"
base_dn = "{ld_unix_groups_dn}"
search_filter = '(cn={value})'
guitype = "hidden"
untrusted = True
opt = ("ur_unix_group_name_exists",)
metavalue = "GROUP"
def init(self):
self.label = _("Group")
self.help = _("set the group name")
def choice(self):
if self.Get('cl_unix_action') == Actions.GroupDel:
primary_groups = map(int, self.get_primary_gids())
return [(group.group_name,
"%s (%s)" % (group.group_name, group.comment))
for group in self.iterate_ldap_group("cn=*")
if group.gid not in primary_groups]
else:
return [(group.group_name,
"%s (%s)" % (group.group_name, group.comment))
for group in self.iterate_ldap_group("cn=*")]
def raiseWrongChoice(self, name, choiceVal, value, error):
if self.Get('cl_unix_action') == Actions.GroupDel:
group = self.search_ldap_group_name(value)
if group:
users = ", ".join(user.username for user in
self.iterate_ldap_user(
"gidNumber=%d" % group.gid))
if users:
raise VariableError(
_("Group {group} is primary group for users {users}"
).format(group=value, users=users))
if not value:
raise VariableError(_("Choice group"))
raise VariableError(_("Group %s not found") % value)
class VariableUrUnixBaseDir(Variable):
"""
Базовая директория для нового пользователя
"""
value = "/home"
opt = ('-b', '--base-dir')
metavalue = "BASE_DIR"
def init(self):
self.label = _("Base directory")
self.help = _("base directory for the home directory of new account")
class VariableUrUnixComment(ExistsUserHelper, UnixActionHelper, Variable):
"""
Описание учётной записи
"""
attribute = "comment"
value_format = "{ldap.ld_base_root.capitalize()} user"
opt = ('-c', '--comment')
metavalue = "COMMENT"
def init(self):
self.label = _("Comment")
self.help = _("set comment of the account")
def get_new(self):
return self._value_formatter.format(self.value_format, self.Get)
class VariableUrUnixGroupComment(UnixGroupHelper, UnixActionHelper, Variable):
"""
Комментарий к группе
"""
value_format = "{ldap.ld_base_root.capitalize()} group"
opt = ('-c', '--comment')
metavalue = "COMMENT"
def init(self):
self.label = _("Comment")
self.help = _("set comment of the group")
def get_new(self):
return self._value_formatter.format(self.value_format, self.Get)
def get_exists(self):
return self.Get('ur_unix_group_comment_exists')
class VariableUrUnixGroupCount(UnixGroupHelper, UnixActionHelper,
ReadonlyVariable):
"""
Количество групп
"""
type = "int"
def get_exists(self):
return len(self.ldap_group_list())
class VariableUrUnixGroupCommentExists(UnixGroupHelper, UnixActionHelper,
Variable):
"""
Комментарий к группе
"""
def get_exists(self):
group_name = self.Get('ur_unix_group_name')
if group_name:
group = self.search_ldap_group_name(group_name)
if group:
return group.comment
return ""
class VariableUrUnixHomePath(ExistsUserHelper, UnixActionHelper, Variable):
"""
Путь до домашней директории
"""
value_format = "{unix.ur_unix_base_dir}/{unix.ur_unix_login}"
opt = ('-d', '--home-dir')
metavalue = "HOME_DIR"
check_after = ["ur_unix_login"]
def init(self):
self.label = _("Home directory")
self.help = _("set home directory of the account")
def get_exists(self):
return self.Get('ur_unix_home_path_exists')
def get_new(self):
return self._value_formatter.format(self.value_format, self.Get)
def check_exists(self, value):
if "," in value:
raise VariableError(_("Wrong home directory"))
if not value.startswith('/'):
raise VariableError(_("Home directory path must be absolutly"))
class VariableUrUnixHomePathExists(ExistsUserHelper, UnixActionHelper,
ReadonlyVariable):
"""
Путь до домашней директории
"""
attribute = "homedir"
class VariableUrUnixHomePathMove(Variable):
"""
Перемещать домашнуюю пользовательскую директорию
"""
type = "bool"
opt = ('-m', '--move-home')
value = "off"
def init(self):
self.label = _("Move home directory")
self.help = _("move contents of the home directory to the new location")
def check_on(self):
new_path = self.Get('ur_unix_home_path')
old_path = self.Get('ur_unix_home_path_exists')
if new_path == old_path:
raise VariableError(_("You should change home directory"))
if path.exists(new_path):
raise VariableError(
_("New home directory %s exists") % new_path)
if not path.exists(old_path):
raise VariableError(
_("Previous home directory %s not found") % old_path)
class VariableUrUnixPrimaryGroup(ExistsUserHelper, UnixGroupHelper,
UnixActionHelper, Variable):
"""
ID основной группы
"""
attribute = "gid"
type = "choiceedit"
opt = ('-g', '--gid')
metavalue = "GROUP"
default_value = "default"
def init(self):
self.label = _("Primary group")
self.help = _("set name or ID of primary group of the account "
"('default' value for create default group)")
def get_new(self):
return self.default_value
def get_exists(self):
value = str(ExistsUserHelper.get_exists(self))
if value:
return str(self.gid_to_name(value))
def set(self, value):
if self._new(self.Get('cl_unix_action')):
if value == self.Get('ur_unix_login'):
return self.default_value
return str(self.gid_to_name(value))
def choice_new(self):
return ([(self.default_value, _("Default"))]
+ self.ldap_group_list())
def choice_exists(self):
return self.ldap_group_list()
def check_new(self, value):
if not value:
raise VariableError(_("You should specify primary group ID"))
# if value != "auto":
if value != self.default_value:
self.check_group(value)
def check_exists(self, value):
if not value:
raise VariableError(_("You should specify primary group ID"))
# if value != "auto":
if value:
self.check_group(value)
def raiseWrongChoice(self, name, choiceVal, value, error):
raise VariableError(_("Group %s not found") % value)
class VariableUrUnixGid(UnixGroupHelper, ReadonlyVariable):
"""
ID основной группы пользователя
"""
type = "int"
def get(self):
group_name = self.Get('ur_unix_primary_group')
print group_name
if (group_name and
group_name != VariableUrUnixPrimaryGroup.default_value):
ldap_group = self.search_ldap_group_name(group_name)
return str(ldap_group.gid)
else:
return self.Get('ur_unix_next_gid')
class VariableUrUnixGroupId(LdapSearchHelper, UnixActionHelper, Variable):
"""
ID группы
"""
base_dn = "{ld_unix_groups_dn}"
search_filter = '(gidNumber={value})'
type = "int"
opt = ('-g', '--gid')
metavalue = "GID"
def init(self):
self.label = _("Group ID")
self.help = _("set the group ID")
def get_new(self):
return self.Get('ur_unix_next_gid')
def get_exists(self):
return self.Get('ur_unix_group_id_exists')
def check_new(self, value):
if not value:
raise VariableError(_("You should specify group ID"))
if self.check_name(value):
raise VariableError(_("Group ID already exists"))
def check_exists(self, value):
old_value = self.Get('ur_unix_group_id_exists')
if not value:
raise VariableError(_("You should specify group ID"))
if value != old_value and self.check_name(value):
raise VariableError(_("Group ID already exists"))
class VariableUrUnixGroupIdExists(UnixGroupHelper, LdapSearchHelper,
UnixActionHelper, Variable):
"""
ID группы
"""
type = "int"
def get_exists(self):
group_name = self.Get('ur_unix_group_name')
if group_name:
group = self.search_ldap_group_name(group_name)
if group:
return str(group.gid)
return ""
class VariableUrUnixUid(UnixUserHelper, UnixActionHelper, Variable):
"""
UID пользователя
"""
type = "int"
opt = ('-u', '--uid')
metavalue = "UID"
value = ""
def init(self):
self.label = _("User ID")
self.help = _("set user ID of the account")
def get_new(self):
return self.Get('ur_unix_next_uid')
def get_exists(self):
login = self.Get('ur_unix_login')
if login:
return str(self.search_ldap_user_name(login).uid)
def check_new(self, value):
user = self.search_ldap_user_id(value)
if user:
raise VariableError(_("Uid %s is used by user %s")
% (user.uid, user.username))
user = self.search_system_user_id(value)
if user:
raise VariableError(_("Uid %s is used by system user %s")
% (user.uid, user.username))
class VariableUrUnixGroups(UnixGroupHelper, UnixActionHelper, Variable):
"""
Список груп
"""
type = "choiceedit-list"
opt = ("-G", "--groups")
metavalue = "GROUPS"
value = []
def init(self):
self.label = _("Supplimentary groups")
self.help = _("set list of supplementary groups of the account")
def set(self, value):
return map(self.gid_to_name, value)
def get_exists(self):
return self.Get('ur_unix_groups_exists')
def choice(self):
return self.ldap_group_list()
def check(self, value):
for group in value:
self.check_group(group)
class VariableUrUnixGroupsExists(UnixGroupHelper, UnixActionHelper, Variable):
"""
Список груп
"""
type = "list"
value = []
#def get_bylogin(self, login, obj):
# return [x.group_name for x in
# self.iterate_ldap_group("memberUid=%s" % login)]
def get_exists(self):
login = self.Get('ur_unix_login')
if login:
return [x.group_name for x in
self.iterate_ldap_group("memberUid=%s" % login)]
return []
class VariableUrUnixGroupsAdd(UnixGroupHelper, UnixActionHelper, Variable):
"""
Список групп в которые необходимо добавить пользователя
"""
type = "choiceedit-list"
opt = ("-a", "--append")
metavalue = "GROUPS"
value = []
def init(self):
self.label = _("Include to groups")
self.help = _("include user into groups")
def set(self, value):
return map(self.gid_to_name, value)
def get_exists(self):
exists_groups = set(self.Get('ur_unix_groups_exists'))
replace_group = set(self.Get('ur_unix_groups'))
return sorted(list(replace_group - exists_groups))
def choice_exists(self):
login = self.Get('ur_unix_login')
if login:
exists_groups = self.Get('ur_unix_groups_exists')
return (x for x in self.ldap_group_list()
if x[0] not in exists_groups)
return []
def check_exists(self, value):
exists_groups = self.Get('ur_unix_groups_exists')
replace_groups = self.Get('ur_unix_groups')
if set(exists_groups) != set(replace_groups):
raise VariableError(_(
"Appending user to groups unavailable "
"with the replace groups using"))
login = self.Get('ur_unix_login')
groups = self.ldap_group_names()
failed = [x for x in value if x not in groups]
if failed:
raise VariableError(
_("Wrong groups {groups}").format(
groups=", ".join(failed)))
self.check_special(value, exists_groups, login)
def check_special(self, value, exists_groups, login):
already_exists = [x for x in value if x in exists_groups]
if already_exists:
raise VariableError(
_("User {user} already exist in groups {groups}").format(
groups=", ".join(already_exists), user=login))
def humanReadable(self):
if not self.Get():
return _("Not change")
class VariableUrUnixGroupsDel(VariableUrUnixGroupsAdd):
"""
Список групп из которых необходимо исключить пользователя
"""
type = "choiceedit-list"
opt = ("-r", "--remove")
metavalue = "GROUPS"
value = []
def init(self):
self.label = _("Exclude from groups")
self.help = _("exclude user from groups")
def get_exists(self):
exists_groups = set(self.Get('ur_unix_groups_exists'))
replace_groups = set(self.Get('ur_unix_groups'))
return sorted(list(exists_groups - replace_groups))
def choice_exists(self):
login = self.Get('ur_unix_login')
if login:
exists_groups = self.Get('ur_unix_groups_exists')
return (x for x in self.ldap_group_list()
if x[0] in exists_groups)
return []
def check_special(self, value, exists_groups, login):
not_exists = [x for x in value if x not in exists_groups]
if not_exists:
raise VariableError(
_("User {user} is not exist in groups {groups}").format(
groups=", ".join(not_exists), user=login))
class VariableUrUnixSkel(Variable):
"""
Skel директория
"""
opt = ("-k", "--skel")
metavalue = "SKEL_DIR"
value = "/etc/skel"
def init(self):
self.label = _("Skeleton directory")
self.help = _("set skeletion directory for new account")
class VariableUrUnixCreateHomeSet(Variable):
"""
Создавать домашнюю директорию пользователю
"""
type = "bool"
opt = ("-m", "--create-home")
value = "off"
check_after = ["ur_unix_home_path"]
def init(self):
self.label = _("Create home directory")
self.help = _("create the user's home directory")
def check_on(self):
home_path = self.Get('ur_unix_home_path')
if path.exists(home_path):
raise VariableError(
_("Home directory %s already exists") % home_path)
class VariableUrUnixPw(Variable):
"""
Пароль пользователя
"""
type = "password"
opt = ("-p", "--password")
value = ""
untrusted = True
metavalue = "PASSWORD"
def init(self):
self.label = _("Password")
self.help = _("set user password")
def check(self, value):
delete_pw = self.GetBool('ur_unix_pw_delete_set')
change_lock = (self.GetBool('ur_unix_lock_set') !=
self.GetBool('ur_unix_lock_exists_set'))
if (self.Get('cl_unix_action') == Actions.Passwd and
not delete_pw and not change_lock and not value):
raise PasswordError(_("Specify user password"))
class VariableUrUnixPwSet(UnixActionHelper, UnixUserHelper, ReadonlyVariable):
"""
Указан ли пароль у пользователя
"""
type = "bool"
def init(self):
self.label = _("Password")
def get_exists(self):
username = self.Get('ur_unix_login')
pw = self.get_password_hash(username)
if pw and pw != self.DeletedPassword:
return "on"
else:
return "off"
class VariableUrUnixPwDeleteSet(Variable):
"""
Удалить пароль пользователя
"""
type = "bool"
value = "off"
opt = ("-d", "--delete")
def init(self):
self.label = _("Remove user password")
self.help = _("delete the password for the named account")
class VariableUrUnixHash(HashHelper, ReadonlyVariable):
"""
Хэш пароля
"""
source = "unix.ur_unix_pw"
class VariableUrUnixUserObject(UnixUserHelper, UnixActionHelper,
ReadonlyVariable):
"""
Объект данных пользователя
"""
def get_exists(self):
login = self.Get('ur_unix_login')
if login:
return self.search_ldap_user_name(login) or ""
return ""
class VariableUrUnixShell(ExistsUserHelper, UnixActionHelper, Variable):
"""
Командная оболочка по умолчанию для пользователя
"""
attribute = "shell"
opt = ("-s", "--shell")
metavalue = "SHELL"
def init(self):
self.label = _("Shell")
self.help = _("login shell of the account")
def get_new(self):
return "/bin/bash"
class VariableUrUnixVisibleSet(ExistsUserHelper, UnixActionHelper, Variable):
"""
Виден ли пользователь
"""
attribute = "visible"
type = "bool"
opt = ("-v", "--visible")
def init(self):
self.label = _("Visible")
self.help = _("set visible of the account")
def get_new(self):
return "on"
class VariableUrUnixLockSet(ExistsUserHelper, UnixActionHelper, Variable):
"""
Виден ли пользователь
"""
attribute = "lock"
type = "bool"
opt = ("-l", "--lock")
value = "off"
def init(self):
self.label = _("Locked")
self.help = _("lock the account")
class VariableUrUnixLockExistsSet(ExistsUserHelper, UnixActionHelper, Variable):
"""
Виден ли пользователь
"""
type = "bool"
attribute = "lock"
value = "off"
class VariableUrUnixVisibleFlag(UnixUserHelper, ReadonlyVariable):
"""
Значение используемое для шаблона
"""
def get(self):
return self.visible_to_flag(self.GetBool('ur_unix_visible_set'))
class VariableUrUnixLockFlag(UnixUserHelper, ReadonlyVariable):
"""
Значение используемое для шаблона
"""
def get(self):
return self.lock_to_flag(self.GetBool('ur_unix_lock_set'))
class VariableUrUnixNextUid(LdapMaxHelper, ReadonlyVariable):
"""
Следующий свободный Uid
"""
base_dn = "{ld_unix_users_dn}"
search_filter = "uid=*"
attr = "uidNumber"
def get(self):
value = self.get_max()
if value is None:
return self.Get('ur_unix_min_uid')
else:
return str(value + 1)
class VariableUrUnixNextGid(LdapMaxHelper, ReadonlyVariable):
"""
Следующий свободный Uid
"""
base_dn = "{ld_unix_groups_dn}"
search_filter = "cn=*"
attr = "gidNumber"
def get(self):
value = self.get_max()
if value is None:
return self.Get('ur_unix_min_gid')
else:
return str(value + 1)
class VariableUrUnixMinUid(Variable):
"""
Минимальный uid
"""
type = "int"
value = "10000"
class VariableUrUnixMinGid(Variable):
"""
Минимальный uid
"""
type = "int"
value = "10000"
class VariableUrUnixGroupUsers(UnixGroupHelper, ReadonlyVariable):
"""
Текущий список пользователей в группе
"""
type = "list"
def init(self):
self.label = _("Users")
def get(self):
group_name = self.Get('ur_unix_group_name')
if group_name:
group = self.search_ldap_group_name(group_name)
if group:
return group.user_list
return []
class VariableUrUnixGroupUsersAdd(UnixUserHelper, Variable):
"""
Пользователи добавляемые в группу
"""
type = "choiceedit-list"
opt = ("-a", "--add")
value = []
metavalue = "USERS"
def init(self):
self.label = _("Include in group")
self.help = _("add members")
def choice(self):
if self.Get('ur_unix_group_name'):
exists_users = self.Get('ur_unix_group_users')
return (x for x in self.ldap_user_list() if
x[0] not in exists_users)
return []
def get(self):
exists_users = set(self.Get('ur_unix_group_users'))
replace_users = set(self.Get('ur_unix_group_users_replace'))
return sorted(list(replace_users - exists_users))
def check(self, value):
exists_users = self.Get('ur_unix_group_users')
replace_users = self.Get('ur_unix_group_users_replace')
if set(exists_users) != set(replace_users):
raise VariableError(_(
"Appending users to group unavailable "
"with the replace user using"))
group = self.Get('ur_unix_group_name')
users = self.ldap_user_names()
failed = [x for x in value if x not in users]
if failed:
raise VariableError(
_("Wrong users {users}").format(
users=", ".join(failed)))
already_exists = [x for x in value if x in exists_users]
if already_exists:
raise VariableError(
_("Users {users} already exist in group {group}").format(
users=", ".join(already_exists), group=group))
class VariableUrUnixGroupUsersReplace(UnixUserHelper, UnixActionHelper,
Variable):
"""
Замена всех пользователей в группе
"""
type = "choiceedit-list"
opt = ("-U ", "--users")
value = []
metavalue = "USERS"
def init(self):
self.label = _("Users")
self.help = _("new user list of group")
def get_exists(self):
return list(sorted(self.Get('ur_unix_group_users')))
def choice_exists(self):
return self.ldap_user_list()
def check_exists(self, value):
users = self.ldap_user_names()
failed = [x for x in value if x not in users]
if failed:
raise VariableError(
_("Wrong users {users}").format(
users=", ".join(failed)))
class VariableUrUnixGroupUsersDel(UnixUserHelper, Variable):
"""
Пользователи добавляемые в группу
"""
type = "choiceedit-list"
opt = ("-r", "--remove")
value = []
metavalue = "USERS"
def init(self):
self.label = _("Exclude from groups")
self.help = _("remove members")
def choice(self):
exists_users = self.Get('ur_unix_group_users')
return (x for x in self.ldap_user_list() if
x[0] in exists_users)
def get(self):
exists_users = set(self.Get('ur_unix_group_users'))
replace_users = set(self.Get('ur_unix_group_users_replace'))
return sorted(list(exists_users - replace_users))
def check(self, value):
exists_users = self.Get('ur_unix_group_users')
replace_users = self.Get('ur_unix_group_users_replace')
if set(exists_users) != set(replace_users):
raise VariableError(_(
"Removing users from group unavailable "
"with the replace user using"))
if not exists_users and value:
raise VariableError(_("Group has not members"))
group = self.Get('ur_unix_group_name')
users = self.ldap_user_names()
failed = [x for x in value if x not in users]
if failed:
raise VariableError(
_("Wrong users {users}").format(
users=", ".join(failed)))
not_exists = [x for x in value if x not in exists_users]
if not_exists:
raise VariableError(
_("Users {users} are not exist in group {group}").format(
users=", ".join(not_exists), group=group))
def humanReadable(self):
if not self.Get():
return _("Not change")
class VariableUrUnixGroupNewname(UnixGroupHelper, Variable):
opt = ("-n", "--new-name")
value = ""
metavalue = "NEW_GROUP"
def init(self):
self.label = _("Group name")
self.help = _("use NEW_GROUP name by GROUP")
def get(self):
return self.Get('ur_unix_group_name')
def check(self, value):
if value == self.Get('ur_unix_group_name'):
return
#raise VariableError(_("The new group name is the same as the old"))
if self.search_ldap_group_name(value):
raise VariableError(
_("Group {name} already exists").format(name=value))
def humanReadable(self):
value = self.Get()
if not value:
return _("Not change")
return value
class VariableUrUnixGroupShow(UnixGroupHelper, UnixActionHelper, Variable):
"""
Группа
"""
type = "choice"
opt = ["-G", "--group"]
metavalue = "GROUP"
def init(self):
self.label = _("Group name")
self.help = _("show group")
def get(self):
return "all"
def choice_exists(self):
return ([("all", _("All"))]
+ self.ldap_group_list())
class VariableUrUnixUserShow(UnixUserHelper, UnixActionHelper, Variable):
"""
Группа
"""
type = "choice"
opt = ["-U", "--user"]
metavalue = "USER"
def init(self):
self.label = _("login")
self.help = _("show user")
def get(self):
return "all"
def choice_exists(self):
try:
return ([("all", _("All"))]
+ self.ldap_user_list())
except LDAPConnectError as s:
raise VariableError(str(s))
class VariableUrUnixUserCount(UnixUserHelper, UnixActionHelper,
ReadonlyVariable):
"""
Количество пользователей
"""
type = "int"
def get_exists(self):
return len(self.ldap_user_list())
class VariableClUnixGroupAliases(ReadonlyVariable):
"""
Алиасы для переменных
"""
type = "table"
value = [('name', 'ur_unix_group_name'),
('id', 'ur_unix_group_id'),
('comment', 'ur_unix_group_comment'),
('users', 'ur_unix_group_users')]
class VariableClUnixGroupFields(Variable):
"""
Список полей для вывода данных группы
"""
type = "choice-list"
element = "selecttable"
opt = ["--fields"]
metavalue = "FIELDS"
def init(self):
self.label = _("Fields")
self.help = _("fields for display")
def choice(self):
data = self.Get('cl_unix_group_aliases')
return [(x, self.parent.getInfo(y).label) for x, y in data]
def get(self):
return [x for x, y in self.Get('cl_unix_group_aliases')]
class VariableClUnixGroupShowFields(ReadonlyVariable):
"""
Список переменных полей при отображении списка групп
"""
type = "list"
def get(self):
mapping = dict(self.Get('cl_unix_group_aliases'))
return [mapping[x] for x in self.Get('cl_unix_group_fields')]
class VariableClUnixUserAliases(ReadonlyVariable):
"""
Алиасы для переменных
"""
type = "table"
value = [
('login', 'ur_unix_login'),
('uid', 'ur_unix_uid'),
('gid', 'ur_unix_primary_group'),
('comment', 'ur_unix_comment'),
('lock', 'ur_unix_lock_set'),
('visible', 'ur_unix_visible_set'),
('groups', 'ur_unix_groups'),
('home', 'ur_unix_home_path'),
('shell', 'ur_unix_shell'),
('password', 'ur_unix_pw_set'),
]
class VariableClUnixUserFields(FieldsHelper, Variable):
"""
Список полей для вывода данных группы
"""
alias_variable = "cl_unix_user_aliases"
class VariableClUnixUserShowFields(ShowFieldsHelper, ReadonlyVariable):
"""
Список переменных полей при отображении списка групп
"""
alias_variable = "cl_unix_user_aliases"
source_variable = "cl_unix_user_fields"