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

n7taea2i  于 2023-01-04  发布在  Python
关注(0)|答案(3)|浏览(148)

嘿,所以我试图使相同的脚本从powershell在python,但我不能得到它的权利,也许你可以帮助我,所以脚本是这样的:
1.打开包含用户信息的csv文件
1.为csv文件中的每一行创建用户
csv看起来像这样:

powershell脚本工作正常,外观如下:

# 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"
}

在Python中是这样的:

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

我该怎么补救呢?

nle07wnf

nle07wnf1#

好吧,我做到了,工程都有或没有功能:

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

yb3bgrhw2#

# 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。
1.修改脚本,为以下变量设置适当的值:
1.$ou:这是要在其中创建新用户的组织单位(OU)的唯一判别名(DN)。
1.$csvFile:这是包含要导入的用户记录的CSV文件的路径。
1.确保CSV文件具有脚本中指定的适当列。
1.打开PowerShell窗口并导航到保存脚本的目录。
1.使用以下命令运行脚本:.\Import-ADUsers.ps1该脚本将读取CSV文件,为文件中的每条记录创建一个新的用户对象,并为每个用户设置指定的属性。
请注意,您需要在计算机上安装Active Directory模块,并且需要以管理权限运行脚本。

42fyovps

42fyovps3#

# 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和panda。
1.导入pyad和panda模块。
1.使用提供的域名和身份证明连接到AD服务器。pyad.set_defaults()函数用于设置连接的默认用户名和密码。pyad.adserver.ADServer.from_domain_name()函数用于基于提供的域名创建AD服务器对象。
1.使用www.example.com _csv()函数将CSV文件读入Pandas数据框pandas.read。
1.使用df.iterrows()函数迭代DataFrame的行,对于每一行,脚本提取相关列的值(例如,名、姓、电子邮件、密码)并将它们存储在变量中。
1.使用pyad.aduser.ADUser.create()方法创建新的AD用户。name参数指定用户的全名,upn参数指定用户主体名称(电子邮件地址),password参数指定用户的密码。ou参数指定要在其中创建用户的AD组织单位的可分辨名称。
1.使用'user.update_attribute()为用户设置其他属性

相关问题