Trying to write a program that will look at all users in AD and place them in the correct ADGroup based on location, job title, and job code. Currently I am using a query to pull all the users by department number. Which is working fine but the output I am getting is in a giant list that is formatted like below:
JavaScript
x
2
1
[{'physicalDeliveryOfficeName': 'Denver, Colorado', 'title': 'Logistics Account Executive Trainee', 'cn': 'Jim Beam'}, {'physicalDeliveryOfficeName': 'Denver, Colorado', 'title': 'Logistics Account Executive', 'cn': 'Joseph Coots'},
2
I am wanting to change the formatting so that it can actually be read and uploaded to a CSV file for latter use. Below is the code I have so far.
JavaScript
1
38
38
1
from sqlite3 import Row
2
from unicodedata import name
3
from pyad import*
4
from pyad import adquery
5
import pyad.adquery
6
import re
7
import csv
8
9
10
11
UserName = "122"
12
13
q = pyad.adquery.ADQuery()
14
15
q.execute_query(
16
attributes = ["cn","title", "physicalDeliveryOfficeName"],
17
where_clause = f"departmentNumber = '{UserName}'",
18
base_dn="OU=*** Users,OU=**,DC=***,DC=com"
19
)
20
21
22
23
result = list(q.get_results())
24
for list in result():
25
namead = list["cn"]
26
27
name = namead.pop
28
29
# group = pd.Dataframe({'P1': [x['parameter1'] for x in result], 'P2':[x['parameter2'] for x in result], 'P3':[x['parameter3'] for x in result]}) #'P3':[x['parameter3'] for x in result]
30
31
# f= open(r'C:UsersjustinDenver.csv', 'w+', newline='')
32
33
# writer = csv.writer(f)
34
35
# writer.writerow(group)
36
37
print(name)
38
Advertisement
Answer
Assuming the formatting of the output is consistent, I’d say the following solves your problem:
JavaScript
1
6
1
import pandas as pd
2
# result = [{'physicalDeliveryOfficeName': 'Denver, Colorado', 'title': 'Logistics Account Executive Trainee', 'cn': 'Jim Beam'}, {'physicalDeliveryOfficeName': 'Denver, Colorado', 'title': 'Logistics Account Executive', 'cn': 'Joseph Coots'}]
3
4
result_dataframe = pd.concat([pd.DataFrame.from_dict(d, orient= "index").transpose() for d in result]).reset_index(drop = True)
5
result_dataframe.to_csv("C:/Users/justin/Denver.csv")
6