nextcloud容器内批量新建用户

1.文章背景:

用docker搭建nextcloud私人网盘后,需要把mysql数据库的用户信息迁移过来,即批量的新建用户,但是在进入到nextcloud 容器中后,缺少必须的环境(python expect),之前写的脚本也不能用了。

博主开始的想法是在容器中安装python环境,但是发现这是一个麻烦事(其实是因为自己没有搞定),容器内依然缺这缺那,为什么不在宿主机上跑脚本,进入到容器内批量新建呢?

2.实施思路

博主的大致思路是这样的:
先写一个python程序,读取所需要的用户数据,将每一条新建用户需要的数据(username,password,group)传到shell脚本中,然后在python中运行这个shell脚本。

3.实现代码

python部分:

import pymysql
from subprocess import call
#需要连接数据库的信息
config = {
    "host": "your ip",
    "user": "your username",
    "password": "your password",
    "db": "your db",
    "port": 3306,
    "charset": "utf8"
}

db = pymysql.connect(**config)
cursor = db.cursor()
sql = "select * from user "
try:
    cursor.execute(sql)
    results = cursor.fetchall()
    for result in results:
    	#你需要新建用户的信息
        username = result[1]
        password = result[2]
        #email = result[5]
        grouptype = result[6]

        if grouptype == 1:
            group = "users"
        elif grouptype == 2:
            group = "RegionalAdmin"
        else:
            group = "admin"
        #print(username, password, group)
        #传递参数到新建用户脚本,脚本路径换成你自己的
        call(["/home/ubuntu/src/create_user_owncloud.sh %s %s %s" % (username,password,group)],shell=True)	

except:
    print("error!!!!!!")
db.close()

shell部分
set timeout 设置超时时间,-1:永不超时。
关于expect命令不熟悉的同学可以查看这篇博客:Linux 下 expect 脚本语言中交互处理常用命令
关于docker命令可以查看我的另一篇博客:docker使用中的常见命令

#!/usr/bin/expect
set timeout -1
set username [lindex $argv 0]
set password [lindex $argv 1]
set group [lindex $argv 2]
#set email [lindex $argv 3]
spawn docker exec -it 4d497f82500f /bin/bash		#进入到docker容器
expect "#"
send "sudo -u www-data php /var/www/html/occ user:add --group=$group $username\r"		#新建用户命令
expect {
        "*password*"
        {send "$password\r";exp_continue;}
        "*password*"
        {send "$password\r";exp_continue;}
        "#"
        {send "exit\r";}
}
expect eof

4.运行结果

下图为linux中的部分截图,因nextcloud用户名规则有一定要求:Only the following characters are allowed in a username: “a-z”, “A-Z”, “0-9”, and “_.@-’”,所以数据库中部分不符合用户名规则的用户无法新建。
在这里插入图片描述
nextcloud用户:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值