签到成功

知道了

CNDBA社区CNDBA社区

Python创建Linux下用户--采用读取配置文件的方式

2022-02-09 22:20 908 0 原创 Python
作者: hbhe0316

1.Python代码

http://www.cndba.cn/hbhe0316/article/106636
http://www.cndba.cn/hbhe0316/article/106636
http://www.cndba.cn/hbhe0316/article/106636
http://www.cndba.cn/hbhe0316/article/106636
http://www.cndba.cn/hbhe0316/article/106636

[root@njmon python]# cat username.py 
#!/usr/bin/env python
import os
import re
def get_username_func():
    global username
    global password
    file = open("/home/python/username.txt", "r")
    li = []
    for line in file.readlines():
        a = line.strip("/n")
        print('username is %s' % line.strip("/n").split(",")[0])
        print('password is %s' % line.strip("/n").split(",")[1])
        username = line.strip("/n").split(",")[0]
        print(username)
        password = line.strip("/n").split(",")[1]
        print(password)
        create_user_func(username,password)
        file.close()

def create_user_func(username,password):
    with open('/etc/passwd', 'r') as fd:
        for line in fd:
            matchusername = re.search(r'%s' % username, line, re.I)
    if not matchusername:
        os.system('useradd  %s -p %s' % (username,password))
        print('%s is create successfully' % username)
    else:
        print('%s is already exists.' % username)

def main():
    get_username_func()

if __name__ == "__main__":
    main()

2.配置文件http://www.cndba.cn/hbhe0316/article/106636http://www.cndba.cn/hbhe0316/article/106636http://www.cndba.cn/hbhe0316/article/106636

[root@njmon python]# cat username.txt 
jack,passw0rd
aaron,passw0rd

3.执行效果,如果username存在,则不创建http://www.cndba.cn/hbhe0316/article/106636

http://www.cndba.cn/hbhe0316/article/106636

[root@njmon python]# python username.py 
username is jack
password is passw0rd
jack
passw0rd
jack is create successfully
username is aaron
password is passw0rd
aaron
passw0rd
useradd: user 'aaron' already exists
aaron is create successfully

版权声明:本文为博主原创文章,未经博主允许不得转载。

Python

用户评论
* 以下用户言论只代表其个人观点,不代表CNDBA社区的观点或立场
hbhe0316

hbhe0316

关注

1.只有承认无知,才能装下新的东西; 2.进步来自一点点滴滴的积累; 3.广博让你更优秀,而专业让你无法替代; 4.挫折和失败能够转换为一种财富。

  • 889
    原创
  • 1
    翻译
  • 13
    转载
  • 24
    评论
  • 访问:1038770次
  • 积分:1523
  • 等级:核心会员
  • 排名:第6名
精华文章
    最新问题
    查看更多+
    热门文章
      热门用户
      推荐用户
        Copyright © 2016 All Rights Reserved. Powered by CNDBA · 皖ICP备2022006297号-1·

        QQ交流群

        注册联系QQ