为了账号安全,请及时绑定邮箱和手机立即绑定

从 csv 导入数据并创建 Active Directory 用户列表

从 csv 导入数据并创建 Active Directory 用户列表

慕尼黑8549860 2023-07-11 10:46:37
嘿,所以我试图在 python 中从 powershell 制作相同的脚本,但我无法正确执行,也许你可以帮助我,所以脚本是这样的:打开包含用户信息的 csv 文件为 csv 文件中的每一行创建用户csv 看起来像这样:powershell 脚本工作正常,如下所示:# import moduleImport-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 informationforeach ($user in $users) {# gather user information$fname = $user.'first name'$lname = $user.'last name'$oupath = $user.'ou'#creat new ad user from csv fileNew-ADUser -name "$fname $lname" -GivenName $fname -Surname $lname -UserPrincipalName "$fname.$lname" -Path $oupath -AccountPassword $securedpassword -ChangePasswordAtLogon $true -Enabled $true# echo outputecho "account created for $fname $lname in $oupath"}在Python中是这样的:#import csv and active directory moduleimport csvfrom 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)我怎样才能解决这个问题 ?
查看完整描述

3 回答

?
忽然笑

TA贡献1806条经验 获得超5个赞

好吧,我成功了,无论有没有功能都可以:


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")


查看完整回答
反对 回复 2023-07-11
?
aluckdog

TA贡献1847条经验 获得超7个赞

# 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 = "user@example.com"

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!")

该脚本执行以下步骤:

  1. 使用 pip 命令安装所需的 python 模块 pyad 和 pandas。

  2. 导入 pyad 和 pandas 模块。

  3. 使用提供的域名和凭据连接到 AD 服务器。pyad.set_defaults() 函数用于设置连接的默认用户名和密码。pyad.adserver.ADServer.from_domain_name() 函数用于根据提供的域名创建 AD 服务器对象。

  4. 使用 pandas.read_csv() 函数将 CSV 文件读入 Pandas DataFrame。

  5. 使用 df.iterrows() 函数迭代 DataFrame 的行。对于每一行,脚本提取相关列的值(例如名字、姓氏、电子邮件、密码)并将它们存储在变量中。

  6. 使用 pyad.aduser.ADUser.create() 方法创建新的 AD 用户。name 参数指定用户的全名,upn 参数指定用户主体名称(电子邮件地址),password 参数指定用户的密码。ou 参数指定要在其中创建用户的 AD 组织单位的可分辨名称。

  7. 使用 user.update_attribute() 为用户设置附加属性


查看完整回答
反对 回复 2023-07-11
?
SMILET

TA贡献1796条经验 获得超4个赞

   # Step 1: Import the ActiveDirectory module and connect to the AD server

    

    Import-Module ActiveDirectory

    

    $ad_user = "user@example.com"

    $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!"

  1. 将脚本保存到扩展名为 .ps1 的文件中,例如 Import-ADUsers.ps1。

  2. 修改脚本为以下变量设置适当的值:

  3. $ou:这是您要在其中创建新用户的组织单位 (OU) 的可分辨名称 (DN)。

  4. $csvFile:这是包含要导入的用户记录的 CSV 文件的路径。

  5. 确保 CSV 文件具有脚本中指定的适当列。

  6. 打开 PowerShell 窗口并导航到保存脚本的目录。

  7. 使用以下命令运行脚本: .\Import-ADUsers.ps1 该脚本将读取 CSV 文件,为文件中的每条记录创建一个新的用户对象,并为每个用户设置指定的属性。

    请注意,您需要在计算机上安装 Active Directory 模块,并且需要使用管理权限运行脚本。



查看完整回答
反对 回复 2023-07-11
  • 3 回答
  • 0 关注
  • 155 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信