本文介绍使用Python创建用户信息和初始密码。
1. 从教务系统导出学生信息
可以从教务系统导出学生信息,通常是保存成Excel格式,稍微调整下表格内容,使其格式如下(也可以表格内容不变,修改代码):
班级 学号 姓名
计算2011 201821121027 张*
计算2011 202021121001 钟**
读取Excel文件,保存到列表中,
from openpyxl import load_workbook
from xpinyin import Pinyin
import os
import csv
def get_student_class_id_name(file_workbook, sheet_name='Sheet1'):
wb = load_workbook(file_workbook, read_only=True)
ws = wb[sheet_name]
list_student_class_id_name = list()
p = Pinyin()
for row in ws.iter_rows(min_row=2):
student_class = row[0].value
student_id = row[1].value
student_name_cn = row[2].value
if student_id:
student_name_pinyin = p.get_pinyin(student_name_cn, '')
list_student_class_id_name.append((student_class, student_id, student_name_cn, student_name_pinyin))
return list_student_class_id_name
2. 创建用户信息
用户信息格式如下:
Username:Password:User ID:Group ID:User Info:Home Directory:Default Shell
核心代码如下:
def get_users_file(list_student_class_id_name, start_user_id=None, class_group_id=None):
qiankun:x:qiankun:201112:qiankun:/home/qiankun:/bin/bash
Username:Password:User ID:Group ID:User Info:Home Directory:Default Shell
l_users = list()
user_id = start_user_id
for student_class, student_id, student_name_cn, student_name_pinyin in list_student_class_id_name:
username = 'u{}'.format(student_id)
group_id = class_group_id[student_class]
l = [username, 'x', user_id, group_id,
'{}-{}-{}'.format(student_class, student_id, student_name_cn),
os.path.join('/home/', username), '/bin/bash'
l_users.append(':'.join([str(i) for i in l]))
user_id += 1
return l_users
3. 创建初始密码信息
生成一个文件,每一行的格式为username:password
,核心代码如下:
def get_passwd_file(list_student_class_id_name):
l_passwd = list()
for student_class, student_id, student_name_cn, student_name_pinyin in list_student_class_id_name:
s = 'u{student_id}:{student_id}'.format(student_id=student_id)
l_passwd.append(s)
return l_passwd
完整的源码文件见:create_users_passwd_info.py。