mtes-scripts/scripts/zephir/authorize_user_group.py

181 lines
6.0 KiB
Python
Raw Normal View History

2021-05-07 13:38:20 +02:00
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import sys, getpass, socket
from pyeole.ihm import print_line
from pyeole.ansiprint import print_orange, print_red
from creole.client import CreoleClient
from collections import OrderedDict
2021-07-09 15:04:17 +02:00
from zephir.backend.lib_backend import CxPool
2021-05-07 13:38:20 +02:00
try:
from zephir.zephir_conf.zephir_conf import adresse_zephir
except:
client = CreoleClient()
adresse_zephir = client.get_creole('nom_domaine_machine')
from zephir.lib_zephir import convert
from zephir.lib_zephir import xmlrpclib
from zephir.lib_zephir import EoleProxy
from zephir.lib_zephir import TransportEole
from zephir.lib_zephir import flushed_input
def display_help():
print("Autorise une connexion ssh d'un utilisateur sur un groupe de serveur")
2021-07-09 15:26:47 +02:00
print("{} [numero du groupe] [--user utilisateur]".format(sys.argv[0]))
2021-05-07 13:38:20 +02:00
def argparser():
# récupère l'ID du groupe
arglen = len(sys.argv)
if arglen == 1:
2021-07-09 15:26:47 +02:00
return None, None
2021-05-07 13:38:20 +02:00
if sys.argv[1] in ['-h', '--help']:
display_help()
sys.exit(0)
try:
group_id = int(sys.argv[1])
except:
print_red("\"{}\" n'est pas un ID de groupe valide".format(sys.argv[1]))
display_help()
sys.exit(1)
2021-07-09 15:04:17 +02:00
if sys.argv[2] in ['-u', '--user']:
user = sys.argv[3]
2021-07-09 15:26:47 +02:00
return group_id, user
2021-07-09 15:04:17 +02:00
2021-07-09 15:26:47 +02:00
return group_id, None
2021-05-07 13:38:20 +02:00
def main():
# import des fonctions communes de Zéphir client
2021-07-09 15:26:47 +02:00
group_id, user = argparser()
2021-05-07 13:38:20 +02:00
authentified, proxy = get_pwd(adresse_zephir, 7080)
if authentified == False:
sys.exit(1)
id_variante = ""
try:
groups = {grp_id: (group_name, liste_serveurs) for grp_id, group_name, liste_serveurs in convert(proxy.serveurs.get_groups())[1]}
except xmlrpclib.ProtocolError:
print_red("""Erreur de permissions ou Zéphir non disponible""")
sys.exit(1)
except socket.error, e:
print_red("""Erreur de connexion au serveur Zéphir (%s)""" % str(e))
sys.exit(1)
# on récupère l'ID du groupe concerné
if group_id is None:
print('Liste des groupes :')
for grp_id, group_infos in groups.items():
print(' - ' + str(grp_id) + ' : ' + group_infos[0])
2021-07-09 15:04:17 +02:00
print( ' - N : Créer un nouveau groupe')
2021-05-07 13:38:20 +02:00
while group_id is None:
tmp_group_id = flushed_input("Numéro du groupe : ")
2021-07-09 15:04:17 +02:00
if tmp_group_id == 'N':
group_id = 'N'
liste_serveurs = make_group()
else:
try:
group_id = int(tmp_group_id)
except Exception as err:
print(err)
continue
if not group_id in groups:
print_red('Groupe inconnu')
group_id = None
sys.exit(1)
liste_serveurs = groups[group_id][1]
2021-05-07 13:38:20 +02:00
if user is None:
user = flushed_input("Utilisateur : ")
ret = proxy.serveurs.authorize_user(user,liste_serveurs)
print('Utilisateur {} autorisé à accéder en ssh aux serveurs {}'.format(user, liste_serveurs))
2021-07-09 15:04:17 +02:00
def make_group():
cx_pool = CxPool()
cu = cx_pool.create()
cu.execute("""select libelle,id from modules""")
infos = {}
variante_infos = {}
filename = 'exportation'
server_infos = []
for module_name in cu.fetchall():
module, version = module_name[0].rsplit('-', 1)
infos.setdefault(version, {})[module] = module_name[1]
versions = infos.keys()
versions.sort()
print('Choix de la version :')
for idx, version in enumerate(versions):
print('{}: {}'.format(idx, version))
idx = input('> ')
version = versions[int(idx)]
filename += '-' + version
print
print('Choix du module :')
modules = infos[version].keys()
modules.sort()
for idx, module in enumerate(modules):
print('{}: {}'.format(idx, module))
idx = input('> ')
module = modules[int(idx)]
filename += '-' + module
print
cu.execute("select libelle,id from variantes where module = " + str(infos[version][module]))
for variante_obj in cu.fetchall():
variante_infos[variante_obj[0]] = variante_obj[1]
print('Choix de la variante :')
variantes = variante_infos.keys()
variantes.sort()
for idx, variante in enumerate(variantes):
print('{}: {}'.format(idx, variante))
idx_all = idx + 1
print('{}: toutes les variantes'.format(idx_all))
idx = input('> ')
if idx == idx_all:
variantes = variante_infos.values()
else:
filename += '-' + variantes[idx]
variantes = [variante_infos[variantes[idx]]]
print
for variante in variantes:
cu.execute('select id,ip_publique,rne,libelle from serveurs where variante=' + str(variante))
print("Liste des serveurs : ")
for server in cu.fetchall():
print('{} - {} - {} - {}'.format(server[0], server[1], server[2], server[3]))
server_infos.append(server[0])
return server_infos
2021-05-07 13:38:20 +02:00
def get_pwd(addr, port):
"""lecture d'un login/passwd pour l'application zephir
"""
login_ok = 0
user = "toto"
while login_ok == 0 and user != "":
try:
# flush de l'entrée standard au cas où l'utilisateur aurait
# tapé <entrée> pendant l'Upgrade
termios.tcflush(sys.stdin, termios.TCIOFLUSH)
except:
pass
user = flushed_input("Entrez votre login zephir (rien pour sortir) : ")
if user != "":
passwd = getpass.getpass("Mot de passe zephir pour %s : " % user)
# création du proxy avec zephir
proxy = EoleProxy("https://%s:%s@%s:%s" % (user, passwd, addr, port), transport=TransportEole())
login_ok = 1
try:
res = convert(proxy.get_permissions(user))
except xmlrpclib.ProtocolError:
login_ok = 0
print_line("\n Erreur d'authentification \n")
else:
return False, "! Abandon de la procédure !"
return True, proxy
if __name__ == '__main__':
main()