Here’s an example Go script that reads a CSV file containing user information and creates or updates those users in a FreeIPA server using the FreeIPA API:
package main
import (
"encoding/csv"
"fmt"
"io"
"net/http"
"os"
"strings"
)
func main() {
// Open the CSV file
file, err := os.Open("users.csv")
if err != nil {
fmt.Println("Error opening file:", err)
return
}
defer file.Close()
// Create a CSV reader
reader := csv.NewReader(file)
// Read the header row
header, err := reader.Read()
if err != nil {
fmt.Println("Error reading header row:", err)
return
}
// Find the index of each column in the header row
var (
usernameIndex = -1
givenNameIndex = -1
surnameIndex = -1
emailIndex = -1
)
for i, col := range header {
switch strings.ToLower(col) {
case "username":
usernameIndex = i
case "givenname":
givenNameIndex = i
case "surname":
surnameIndex = i
case "email":
emailIndex = i
}
}
if usernameIndex == -1 || givenNameIndex == -1 || surnameIndex == -1 || emailIndex == -1 {
fmt.Println("Error: CSV file is missing required columns (username, givenName, surname, email)")
return
}
// Loop over the remaining rows in the CSV file
for {
row, err := reader.Read()
if err == io.EOF {
break
} else if err != nil {
fmt.Println("Error reading row:", err)
return
}
// Create or update the user in FreeIPA
username := row[usernameIndex]
givenName := row[givenNameIndex]
surname := row[surnameIndex]
email := row[emailIndex]
err = createUser(username, givenName, surname, email)
if err != nil {
fmt.Println("Error creating or updating user:", err)
return
}
}
fmt.Println("Done!")
}
func createUser(username, givenName, surname, email string) error {
// Create a HTTP client
client := &http.Client{}
// Set up the request
url := "https://ipa.example.com/ipa/session/json"
data := fmt.Sprintf(`{
"method": "user_add",
"params": [
[
"%s"
],
{
"givenname": "%s",
"sn": "%s",
"mail": "%s"
}
],
"id": 0
}`, username, givenName, surname, email)
req, err := http.NewRequest("POST", url, strings.NewReader(data))
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/json")
// Send the request and read the response
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
// Check for errors in the response
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("server returned status code %d", resp.StatusCode)
}
var result struct {
Error *struct {
Message string `json:"message"`
} `json:"error"`
}
err = json.NewDecoder(resp.Body).Decode(&result)
if err != nil {
return err
}
if
## USER
i need a python script which sync users from a csv file to a freeipa server
## ASSISTANT
Certainly! Here's an example Python script that reads a CSV file containing user information and creates or updates those users in a FreeIPA server using the FreeIPA API:
```python
import csv
import json
import requests
# Set up the FreeIPA API endpoint and authentication credentials
url = 'https://ipa.example.com/ipa/session/json'
auth = ('admin', 'password')
# Open the CSV file
with open('users.csv', 'r') as file:
reader = csv.DictReader(file)
# Loop over each row in the CSV file
for row in reader:
# Extract the user data from the row
username = row['username']
givenname = row['givenname']
sn = row['surname']
mail = row['email']
# Create or update the user in FreeIPA
data = {
'method': 'user_add',
'params': [
[username],
{
'givenname': givenname,
'sn': sn,
'mail': mail
}
],
'id': 0
}
response = requests.post(url, auth=auth, json=data)
response_data = response.json()
# Check for errors in the response
if 'error' in response_data:
error = response_data['error']['message']
print(f'Error creating or updating user {username}: {error}')
else:
print(f'Successfully created or updated user {username}')
Note that you’ll need to replace the url and auth variables with the appropriate values for your FreeIPA server. Also, make sure that the CSV file you’re using has columns named username, givenname, surname, and email (or modify the script to use different column names).