-
Notifications
You must be signed in to change notification settings - Fork 0
/
criaUsuario.py
161 lines (130 loc) · 4.98 KB
/
criaUsuario.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
import csv
import ldap
import ldap.modlist as modlist
import hashlib
import httplib2
import os
import base64
import mysql.connector
from apiclient import discovery
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
from email.mime.text import MIMEText
from apiclient import errors
from random import choice
SCOPES = 'https://www.googleapis.com/auth/gmail.send'
CLIENT_SECRET_FILE = 'client_secret.json'
APPLICATION_NAME = 'Geracao de usuario OpenLDAP'
def get_credentials():
home_dir = os.path.expanduser('~')
credential_dir = os.path.join(home_dir, '.credentials')
if not os.path.exists(credential_dir):
os.makedirs(credential_dir)
credential_path = os.path.join(credential_dir,'geracao-usuario-openldap.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(CLIENT_SECRET_FILE, SCOPES)
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store)
print('Armazenando credenciais ' + credential_path)
return credentials
def get_ldap_connection(server, username, password):
l = ldap.initialize(server)
l.protocol_version = ldap.VERSION3
l.bind_s(username, password)
return l
def add_user(connection, dn, attrs):
ldif = modlist.addModlist(attrs)
connection.add_s(dn, ldif)
def get_ldap_user(connection, base_dn, searchScope, searchFilter):
return connection.search_s(base_dn, searchScope, searchFilter)
def get_service():
credentials = get_credentials()
http = credentials.authorize(httplib2.Http())
return discovery.build('gmail', 'v1', http=http)
def novaSenha():
caracters = '0123456789abcdefghijlmnopqrstuwvxz'
senha = ''
for x in range(6):
senha += choice(caracters)
return senha
def create_message(sender, to, subject, message_text):
message = MIMEText(message_text)
message['to'] = to
message['from'] = sender
message['subject'] = subject
return {'raw': base64.urlsafe_b64encode(message.as_string())}
def send_message(service, user_id, message):
try:
message = (service.users().messages().send(userId=user_id, body=message)
.execute())
return message
except errors.HttpError, error:
print 'Ocorreu um erro: %s' % error
def main():
documento = 'usuarios.csv'
#LDAP server configs
server = "ldap://localhost:389"
username = 'cn=Manager,dc=example,dc=com'
password = 'secret'
dn_base = "dc=example,dc=com"
#Gmail configs
sender = '[email protected]'
subject = 'Novo usuario'
user_id = 'me'
#Parametros de conexao
connection_string = {
'user': 'root',
'password': '',
'host': '127.0.0.1',
'database': 'testeInternalSistem',
'port': '3306'
}
print('Abrindo arquivo')
if sum(1 for line in open(documento)) == 0:
print('Nenhuma linha encontrada no arquivo')
else:
with open(documento, 'rb') as ficheiro:
reader = csv.reader(ficheiro, delimiter=';')
print('Lendo linhas')
cnx = mysql.connector.connect(**connection_string)
cursor = cnx.cursor()
for linha in reader:
print(linha)
try:
usuario = linha[0] + "." + linha[1]
senha = novaSenha()
dn = "cn=" + usuario + "," + dn_base
attrs = {}
attrs['objectclass'] = ['top','person']
attrs['cn'] = usuario
attrs['description'] = 'usuario1'
attrs['sn'] = linha[1]
attrs['userPassword'] = hashlib.md5(senha).hexdigest()
print('Criando registro LDAP')
cx = get_ldap_connection(server, username, password)
add_user(cx, dn, attrs)
print('Registro LDAP criado. Usuario: ' + usuario)
'''
filtro = 'cn=' + usuario
print(get_ldap_user(cx, dn_base, ldap.SCOPE_SUBTREE, filtro))
'''
cx.unbind()
print('Salvando usuario no banco de dados')
insert_clause = "INSERT INTO usuario (nome, sobrenome, usuario, senha, estado) values (%s, %s, %s, %s, %s)"
values = (linha[0], linha[1], usuario,attrs['userPassword'], True)
cursor.execute(insert_clause, values)
print('Usuario salvo')
print('Preparando envio de email')
msg_txt = "Seu usuario e '" + usuario + "' e sua senha '" + senha + "'"
send_message(get_service(), user_id, create_message(sender, linha[2], subject, msg_txt))
print('Email enviado')
except ldap.LDAPError, e:
print e
cnx.commit()
cursor.close()
cnx.close()
if __name__ == '__main__':
main()