import data from csv and create list of Active Directory users
Question:
hey so i am trying to make the same script from powershell in python but i cant get it right maybe you can help me out,
so the script is like that:
- opens a csv file with the users information
- create users for each row in the csv file
the csv looks like this:
the powershell scripts works fine looks like this:
# import module
Import-Module ActiveDirectory
# create new password
$securedpassword = ConvertTo-SecureString "abc-123" -AsPlainText -Force
#import csv
$filepath = Read-Host -Prompt "please enter csv path"
#import the file into a variable
$users = Import-Csv $filepath
# loop all rows to gather information
foreach ($user in $users) {
# gather user information
$fname = $user.'first name'
$lname = $user.'last name'
$oupath = $user.'ou'
#creat new ad user from csv file
New-ADUser -name "$fname $lname" -GivenName $fname -Surname $lname -UserPrincipalName "$fname.$lname" -Path $oupath -AccountPassword $securedpassword -ChangePasswordAtLogon $true -Enabled $true
# echo output
echo "account created for $fname $lname in $oupath"
}
and in python like this:
#import csv and active directory module
import csv
from pyad import *
def createuserfromcsv():
#takes full file path for test: c:newusers.csv
file = input('please type your file path + file: ')
data = open(file,encoding="utf-8")
csv_data = csv.reader(data)
data_lines = list(csv_data)
pyad.set_defaults(ldap_server="DC-01-Training.Udemy.training",username="Administrator",password="abc-123")
for line in data_lines[1:]:
user = line[0]
for line in data_lines[1:]:
oupath = line[2]
ou = pyad.adcontainer.ADContainer.from_dn(oupath)
new_user = pyad.aduser.ADUser.create(user,ou,password="abc-123")
print(user)
print(oupath)
how can i fix this ?
Answers:
ok i made it ,works both with or without function:
import csv
from pyad import *
def createuserfromcsv():
#takes full file path
file = input('please type your file path + file: ')
data = open(file,encoding="utf-8")
csv_data = csv.reader(data)
data_lines = list(csv_data)
#load admin information
pyad.set_defaults(ldap_server="DC-01-Training.Udemy.training",username="Administrator",password="abc-123")
for line in data_lines[1:]:
user = line[0]
oupath = line[2]
ou = pyad.adcontainer.ADContainer.from_dn(oupath)
pyad.aduser.ADUser.create(user,ou,password="abc-123")
# Step 1: Import the ActiveDirectory module and connect to the AD server
Import-Module ActiveDirectory
$ad_user = "[email protected]"
$ad_password = "password" | ConvertTo-SecureString -AsPlainText -Force
$ad_credential = New-Object System.Management.Automation.PSCredential -ArgumentList $ad_user, $ad_password
$ad_domain = "example.com"
Connect-AzureAD -Credential $ad_credential -TenantId $ad_domain
# Step 2: Read the CSV file into a variable as an array of objects
$records = Import-Csv -Path "records.csv"
# Step 3: Iterate over the array of objects and create AD users
foreach ($record in $records) {
$first_name = $record.first_name
$last_name = $record.last_name
$email = $record.email
$password = $record.password
# Create the AD user
New-AzureADUser -AccountEnabled $true -DisplayName "$first_name $last_name" -PasswordProfile @{ Password = $password; ForceChangePasswordNextSignIn = $false } -UserPrincipalName $email -GivenName $first_name -Surname $last_name -MailNickname $email
# Set additional attributes for the user
Set-AzureADUser -ObjectId (Get-AzureADUser -Filter "UserPrincipalName eq '$email'").ObjectId -MobilePhone $record.mobile_phone -StreetAddress $record.street_address -City $record.city -State $record.state -PostalCode $record.postal_code -Country $record.country
}
# Step 4: Save the changes to the AD server
Save-AzureAD
Write-Host "Import completed successfully!"
-
Save the script to a file with a .ps1 extension, such as Import-ADUsers.ps1.
-
Modify the script to set the appropriate values for the following variables:
-
$ou: This is the distinguished name (DN) of the organizational unit (OU) in which you want to create the new users.
-
$csvFile: This is the path to the CSV file that contains the user records you want to import.
-
Ensure that the CSV file has the appropriate columns, as specified in the script.
-
Open a PowerShell window and navigate to the directory where the script is saved.
-
Run the script using the following command: .Import-ADUsers.ps1
The script will read the CSV file, create a new user object for each record in the file, and set the specified attributes for each user.
Note that you will need to have the Active Directory module installed on your machine, and you will need to run the script with administrative privileges.
# Step 1: Install the required python modules
!pip install pyad
!pip install pandas
# Step 2: Import the necessary modules in your script
import pyad
import pandas as pd
# Step 3: Connect to the AD server
ad_user = "[email protected]"
ad_password = "password"
ad_domain = "example.com"
pyad.set_defaults(username=ad_user, password=ad_password)
ad_server = pyad.adserver.ADServer.from_domain_name(ad_domain)
# Step 4: Read the CSV file into a Pandas DataFrame
df = pd.read_csv("records.csv")
# Step 5: Iterate over the rows of the DataFrame and create AD users
ou = "OU=Users,DC=example,DC=com" # The distinguished name of the AD organizational unit where you want to create the users
for index, row in df.iterrows():
first_name = row["first_name"]
last_name = row["last_name"]
email = row["email"]
password = row["password"]
# Create the AD user
user = pyad.aduser.ADUser.create(name=f"{first_name} {last_name}", upn=email, password=password, ou=ou)
# Set additional attributes for the user
user.update_attribute("givenName", first_name)
user.update_attribute("sn", last_name)
user.update_attribute("mail", email)
# Step 6: Save the changes to the AD server
ad_server.commit()
print("Import completed successfully!")
This script performs the following steps:
- Installs the required python modules pyad and pandas using the pip command.
- Imports the pyad and pandas modules.
- Connects to the AD server using the provided domain name and credentials. The pyad.set_defaults() function is used to set the default username and password for the connection. The pyad.adserver.ADServer.from_domain_name() function is used to create an AD server object based on the provided domain name.
- Reads the CSV file into a Pandas DataFrame using the pandas.read_csv() function.
- Iterates over the rows of the DataFrame using the df.iterrows() function. For each row, the script extracts the values of the relevant columns (e.g. first name, last name, email, password) and stores them in variables.
- Creates a new AD user using the pyad.aduser.ADUser.create() method. The name argument specifies the full name of the user, the upn argument specifies the user principal name (email address), and the password argument specifies the user’s password. The ou argument specifies the distinguished name of the AD organizational unit where you want to create the user.
- Sets additional attributes for the user using the `user.update_attribute()
hey so i am trying to make the same script from powershell in python but i cant get it right maybe you can help me out,
so the script is like that:
- opens a csv file with the users information
- create users for each row in the csv file
the csv looks like this:
the powershell scripts works fine looks like this:
# import module
Import-Module ActiveDirectory
# create new password
$securedpassword = ConvertTo-SecureString "abc-123" -AsPlainText -Force
#import csv
$filepath = Read-Host -Prompt "please enter csv path"
#import the file into a variable
$users = Import-Csv $filepath
# loop all rows to gather information
foreach ($user in $users) {
# gather user information
$fname = $user.'first name'
$lname = $user.'last name'
$oupath = $user.'ou'
#creat new ad user from csv file
New-ADUser -name "$fname $lname" -GivenName $fname -Surname $lname -UserPrincipalName "$fname.$lname" -Path $oupath -AccountPassword $securedpassword -ChangePasswordAtLogon $true -Enabled $true
# echo output
echo "account created for $fname $lname in $oupath"
}
and in python like this:
#import csv and active directory module
import csv
from pyad import *
def createuserfromcsv():
#takes full file path for test: c:newusers.csv
file = input('please type your file path + file: ')
data = open(file,encoding="utf-8")
csv_data = csv.reader(data)
data_lines = list(csv_data)
pyad.set_defaults(ldap_server="DC-01-Training.Udemy.training",username="Administrator",password="abc-123")
for line in data_lines[1:]:
user = line[0]
for line in data_lines[1:]:
oupath = line[2]
ou = pyad.adcontainer.ADContainer.from_dn(oupath)
new_user = pyad.aduser.ADUser.create(user,ou,password="abc-123")
print(user)
print(oupath)
how can i fix this ?
ok i made it ,works both with or without function:
import csv
from pyad import *
def createuserfromcsv():
#takes full file path
file = input('please type your file path + file: ')
data = open(file,encoding="utf-8")
csv_data = csv.reader(data)
data_lines = list(csv_data)
#load admin information
pyad.set_defaults(ldap_server="DC-01-Training.Udemy.training",username="Administrator",password="abc-123")
for line in data_lines[1:]:
user = line[0]
oupath = line[2]
ou = pyad.adcontainer.ADContainer.from_dn(oupath)
pyad.aduser.ADUser.create(user,ou,password="abc-123")
# Step 1: Import the ActiveDirectory module and connect to the AD server
Import-Module ActiveDirectory
$ad_user = "[email protected]"
$ad_password = "password" | ConvertTo-SecureString -AsPlainText -Force
$ad_credential = New-Object System.Management.Automation.PSCredential -ArgumentList $ad_user, $ad_password
$ad_domain = "example.com"
Connect-AzureAD -Credential $ad_credential -TenantId $ad_domain
# Step 2: Read the CSV file into a variable as an array of objects
$records = Import-Csv -Path "records.csv"
# Step 3: Iterate over the array of objects and create AD users
foreach ($record in $records) {
$first_name = $record.first_name
$last_name = $record.last_name
$email = $record.email
$password = $record.password
# Create the AD user
New-AzureADUser -AccountEnabled $true -DisplayName "$first_name $last_name" -PasswordProfile @{ Password = $password; ForceChangePasswordNextSignIn = $false } -UserPrincipalName $email -GivenName $first_name -Surname $last_name -MailNickname $email
# Set additional attributes for the user
Set-AzureADUser -ObjectId (Get-AzureADUser -Filter "UserPrincipalName eq '$email'").ObjectId -MobilePhone $record.mobile_phone -StreetAddress $record.street_address -City $record.city -State $record.state -PostalCode $record.postal_code -Country $record.country
}
# Step 4: Save the changes to the AD server
Save-AzureAD
Write-Host "Import completed successfully!"
-
Save the script to a file with a .ps1 extension, such as Import-ADUsers.ps1.
-
Modify the script to set the appropriate values for the following variables:
-
$ou: This is the distinguished name (DN) of the organizational unit (OU) in which you want to create the new users.
-
$csvFile: This is the path to the CSV file that contains the user records you want to import.
-
Ensure that the CSV file has the appropriate columns, as specified in the script.
-
Open a PowerShell window and navigate to the directory where the script is saved.
-
Run the script using the following command: .Import-ADUsers.ps1
The script will read the CSV file, create a new user object for each record in the file, and set the specified attributes for each user.Note that you will need to have the Active Directory module installed on your machine, and you will need to run the script with administrative privileges.
# Step 1: Install the required python modules
!pip install pyad
!pip install pandas
# Step 2: Import the necessary modules in your script
import pyad
import pandas as pd
# Step 3: Connect to the AD server
ad_user = "[email protected]"
ad_password = "password"
ad_domain = "example.com"
pyad.set_defaults(username=ad_user, password=ad_password)
ad_server = pyad.adserver.ADServer.from_domain_name(ad_domain)
# Step 4: Read the CSV file into a Pandas DataFrame
df = pd.read_csv("records.csv")
# Step 5: Iterate over the rows of the DataFrame and create AD users
ou = "OU=Users,DC=example,DC=com" # The distinguished name of the AD organizational unit where you want to create the users
for index, row in df.iterrows():
first_name = row["first_name"]
last_name = row["last_name"]
email = row["email"]
password = row["password"]
# Create the AD user
user = pyad.aduser.ADUser.create(name=f"{first_name} {last_name}", upn=email, password=password, ou=ou)
# Set additional attributes for the user
user.update_attribute("givenName", first_name)
user.update_attribute("sn", last_name)
user.update_attribute("mail", email)
# Step 6: Save the changes to the AD server
ad_server.commit()
print("Import completed successfully!")
This script performs the following steps:
- Installs the required python modules pyad and pandas using the pip command.
- Imports the pyad and pandas modules.
- Connects to the AD server using the provided domain name and credentials. The pyad.set_defaults() function is used to set the default username and password for the connection. The pyad.adserver.ADServer.from_domain_name() function is used to create an AD server object based on the provided domain name.
- Reads the CSV file into a Pandas DataFrame using the pandas.read_csv() function.
- Iterates over the rows of the DataFrame using the df.iterrows() function. For each row, the script extracts the values of the relevant columns (e.g. first name, last name, email, password) and stores them in variables.
- Creates a new AD user using the pyad.aduser.ADUser.create() method. The name argument specifies the full name of the user, the upn argument specifies the user principal name (email address), and the password argument specifies the user’s password. The ou argument specifies the distinguished name of the AD organizational unit where you want to create the user.
- Sets additional attributes for the user using the `user.update_attribute()