Bienvenue sur IndexError.

Ici vous pouvez poser des questions sur Python et le Framework Django.

Mais aussi sur les technos front comme React, Angular, Typescript et Javascript en général.

Consultez la FAQ pour améliorer vos chances d'avoir des réponses à vos questions.

Améliorer un script de backup ldap

0 votes

J'ai un script de backup d'un ldap, qui fait le taf, mais qui est loin d'être optimal (il ouvre et ferme sans arrêt tous ses fichiers...)

Critiques, idées ou pointeurs ?

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import argparse
import ldap3
import sys
import yaml
import tarfile

from pprint import pprint
from datetime import datetime


def loadDict(yamlfile):
    """
        Load data from yamlfile, using safe_load
        yamlfile is mandatory
        return a dict{}
    """
    try:
        with open(yamlfile, 'r') as fichier:
            yamlcontenu = yaml.safe_load(fichier)
            return(yamlcontenu)
    except IOError:
        print("Impossible d'ouvrir le fichier ", fichier.name)
        sys.exit(1)


def writeFile(nom, contenu):
    """
        Write contenu into nom as file
        nom and contenu are mandatory (as str)
    """
    try:
        with open(nom, "wt", encoding="UTF-8") as outputfile:
            for line in contenu:
                outputfile.write(line)
            outputfile.write('\n')  # add empty newline
        print(nom + ' OK')
    except IOError:
        print("Impossible d'ouvrir le fichier ", outputfile.name)
        sys.exit(1)


def append2File(nom, contenu):
    """
        Append contenu into nom as file
        nom and contenu are mandatory (as str)
    """
    try:
        with open(nom, "at", encoding="UTF-8") as outputfile:
            for line in contenu:
                outputfile.write(line)
            outputfile.write('\n')  # add empty newline
        print(nom + ' OK')
    except IOError:
        print("Impossible d'ouvrir le fichier ", outputfile.name)
        sys.exit(1)


def getLdapEntries(ldapDict, searchBase, searchFilter):
    """
        connection to LDAP
        search
        return list of entries (as ldap3.dict)
    """
    ldap_dict = loadDict(ldapDict)
    server = ldap3.Server(ldap_dict['host'], get_info=ldap3.ALL, use_ssl=True)
    #searchAttribute = ['objectClass', '*', '+']  # + get_operational_attributes=True
    searchAttribute = ['objectClass', '*']
    searchLeaf = searchBase + ',' + ldap_dict['basedc']
    #search_scope=BASE|LEVEL|SUBTREE (from ldap3.)

    try:
        with ldap3.Connection(server, ldap_dict['who'], ldap_dict['cred'], read_only=True, auto_range=True, raise_exceptions=True) as conn:
            conn.search(searchLeaf, searchFilter, search_scope=ldap3.SUBTREE, attributes=searchAttribute, get_operational_attributes=False) 
            return conn.entries
    except LDAPException as error:
        print("Probleme avec la connexion LDAP:" + error)
        sys.exit(1)


def AddToTar(fichier):
    """
        Create/Open a compressed tarfile and add fichier to it
    """
    archfile = today + '.tar'
    tf = tarfile.open(archfile, 'a')
    tf.add(fichier)
    tf.close()


"""
    Main()
"""

parser = argparse.ArgumentParser(description='Backup PSMN ldap to ldif files.')
parser.add_argument('-d', action='store_true', help='toggle debug ON')
parser.add_argument('-w', action='store_true', help='write ldif extracts')
args = parser.parse_args()

today = datetime.now().strftime('%Y-%m-%d')
if args.d:
    print(today)

"""
    sauvegarde des uid=*,ou=people,dc=example,dc=org
        +cn=*,ou=auto.home,ou=psmn,dc=example,dc=org
"""

basedn = 'ou=people'
filtre = '(&(uid=*))'
liste = getLdapEntries('ldap_psmn.yml', basedn, filtre)

if args.d:
    print(len(liste),"compte(s)")

for entry in liste:
    if args.d:
        print(entry.uid)
        #pprint(entry.entry_to_ldif())
    filename=str(entry.uid) + ".ldif"
    lines=str(entry.entry_to_ldif())
    if args.w:
        writeFile(filename, lines)
    # append auto.home entry to ldif
    basedn = 'ou=auto.home,ou=psmn'
    filtre = '(&(cn=' + str(entry.uid) + '))'
    liste2 = getLdapEntries('ldap_psmn.yml', basedn, filtre)
    for entry2 in liste2:
        if args.d:
            print(entry2.cn)
            #pprint(entry2.entry_to_ldif())
        lines2=str(entry2.entry_to_ldif())
        if args.w:
            append2File(filename, lines2)
    if args.w:
        AddToTar(filename)


"""
    sauvegarde des cn=*,ou=group,dc=example,dc=org
"""

basedn = 'ou=group'
filtre = '(&(cn=*))'
liste = getLdapEntries('ldap_psmn.yml', basedn, filtre)

if args.d:
    print(len(liste),"group(s)")

for entry in liste:
    if args.d:
        print(entry.cn)
        #pprint(entry.entry_to_ldif())
    filename=str(entry.cn) + ".ldif"
    lines=str(entry.entry_to_ldif())
    if args.w:
        writeFile(filename, lines)
        AddToTar(filename)
demandé 30-Jul par GruiicK (140 points)

1 Réponse

0 votes

Il me fallait des vacances, tout simplement :
la fonction AddToTar n'a pas de raison d'être dans ce contexte...

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#

import argparse
import ldap3
import sys
import yaml
import tarfile

from pprint import pprint
from datetime import datetime


def loadDict(yamlfile):
"""
    Load data from yamlfile, using safe_load
    yamlfile is mandatory
    return a dict{}
"""
try:
    with open(yamlfile, 'r') as fichier:
        yamlcontenu = yaml.safe_load(fichier)
        return(yamlcontenu)
except IOError:
    print("Impossible d'ouvrir le fichier ", fichier.name)
    sys.exit(1)


def writeFile(nom, contenu):
"""
    Write contenu into nom as file
    nom and contenu are mandatory (as str)
"""
try:
    with open(nom, "wt", encoding="UTF-8") as outputfile:
        for line in contenu:
            outputfile.write(line)
        outputfile.write('\n')  # add empty newline @end
    print(nom + ' OK')
except IOError:
    print("Impossible d'ouvrir le fichier ", outputfile.name)
    sys.exit(1)


def getLdapEntries(ldapDict, searchBase, searchFilter):
"""
    connection to LDAP
    search
    return list of entries (as ldap3.dict)
"""
ldap_dict = loadDict(ldapDict)
server = ldap3.Server(ldap_dict['host'], get_info=ldap3.ALL, use_ssl=True)
#searchAttribute = ['objectClass', '*', '+']
searchAttribute = ['objectClass', '*']
searchLeaf = searchBase + ',' + ldap_dict['basedc']
#search_scope=BASE|LEVEL|SUBTREE (from ldap3)

try:
    with ldap3.Connection(server, ldap_dict['who'], ldap_dict['cred'], read_only=True, auto_range=True, raise_exceptions=True) as conn:
        conn.search(searchLeaf, searchFilter, search_scope=ldap3.SUBTREE, attributes=searchAttribute, get_operational_attributes=False) 
        return conn.entries
except LDAPException as error:
    print("Probleme avec la connexion LDAP:" + error)
    sys.exit(1)


#def AddToTar(fichier):
#"""
    #Create/Open a compressed tarfile and add fichier to it
#"""
#archfile = today + '.tar'
#tf = tarfile.open(archfile, 'a')
#tf.add(fichier)
#tf.close()


"""
Main()

"""

parser = argparse.ArgumentParser(description='Backup PSMN ldap to ldif files.')
parser.add_argument('-d', action='store_true', help='toggle debug ON')
parser.add_argument('-w', action='store_true', help='write ldif extracts')
args = parser.parse_args()

today = datetime.now().strftime('%Y-%m-%d')
if args.d:
    print(today)

archfile = today + '.tar'
tf = tarfile.open(archfile, 'a')

"""
sauvegarde des uid=*,ou=people,dc=example,dc=org
    +cn=*,ou=auto.home,ou=psmn,dc=example,dc=org
"""

basedn = 'ou=people'
filtre = '(&(uid=*))'
liste = getLdapEntries('ldap_psmn.yml', basedn, filtre)

if args.d:
    print(len(liste),"compte(s)")

for entry in liste:
    if args.d:
        print(entry.uid)
        #pprint(entry.entry_to_ldif())
    filename=str(entry.uid) + ".ldif"
    result1=str(entry.entry_to_ldif())
    # append auto.home entry to ldif
    basedn = 'ou=auto.home,ou=psmn'
    filtre = '(&(cn=' + str(entry.uid) + '))'
    liste2 = getLdapEntries('ldap_psmn.yml', basedn, filtre)
    for entry2 in liste2:
        if args.d:
            print(entry2.cn)
            #pprint(entry2.entry_to_ldif())
        result2=str(entry2.entry_to_ldif())
    lines = result1 + "\n" + result2
    if args.d:
        pprint(lines)
    if args.w:
        writeFile(filename, lines)
        tf.add(filename)

"""
sauvegarde des cn=*,ou=group,dc=example,dc=org
"""

basedn = 'ou=group'
filtre = '(&(cn=*))'
liste = getLdapEntries('ldap_psmn.yml', basedn, filtre)

if args.d:
    print(len(liste),"group(s)")

for entry in liste:
    if args.d:
        print(entry.cn)
        #pprint(entry.entry_to_ldif())
    filename=str(entry.cn) + ".ldif"
    lines=str(entry.entry_to_ldif())
    if args.w:
        writeFile(filename, lines)
        tf.add(filename)

"""
On a finit, on range.
"""
tf.close()
répondu 24-Aou par GruiicK (140 points)
...