• shell 脚本实战笔记(9)--linux自动批量添加用户


    前言:

      添加linux用户帐号,这个相对简单, 在面对集群, 许多机器的时候, 我们该如何去做和实现? 这篇短文, 简单讲解一些思路, 尽可能地涉及周边的一些知识点. 不光是运维人员会面临这个问题, 对一个基于linux平台的集群服务或软件(比如hadoop集群), 有时也会涉及到这块.

    应用场景:
      是以centos 6.4作为演示的系统, 其他的系统有类同, 也有差异, 且以实战演练, 一步步的讲述下流程.

    *) 实战演练
    查阅useradd的使用和参数选项
    useradd --help

    -d, --home-dir HOME_DIR home directory of the new account
    -m, --create-home create the user's home directory
    -p, --password PASSWORD encrypted password of the new account
    -s, --shell SHELL login shell of the new account

    选项-p 能指定密码, -d指定用户主目录, -s指定用户登录shell

    尝试添加用户名: thinkpad, 密码: lenovo
    useradd thinkpad -p lenovo -s /bin/bash
    su thinkpad
    输入密码: lenovo

    第一次su thinkpad成功, 是因为当前的帐号是root, su thinkpad不需要密码验证
    第二次su thinkpad则失败, 说明密码并不是lenovo
    为什么呢? 究其原因, 如参数说明, 该参数指定的password为加密后密码字符串, 那具体采用了那种加密算法?

    我们可以进一步的通过命令手册来查阅
    man useradd

    -p, --passwordPASSWORD
    加密了的密码,就像 crypt(3) 的返回值。默认为禁用密码。

    crypt是个系统函数, 我们继续查阅
    man 3 crypt

    NAME
      crypt, crypt_r - password and data encryption
    
    SYNOPSIS
      #define _XOPEN_SOURCE /* See feature_test_macros(7) */
      #include <unistd.h>
    
      char *crypt(const char *key, const char *salt);
    
      #define _GNU_SOURCE /* See feature_test_macros(7) */
      #include <crypt.h>
    
      char *crypt_r(const char *key, const char *salt,
      struct crypt_data *data);
    
    DESCRIPTION
      key is a user's typed password.
      salt is a two-character string chosen from the set [a–zA–Z0–9./].

    key和salt(两字节)的设置很重要, 于是我们继续编写自己的密码生成器
    编写文件crypt_passwd.cpp

    #define _XOPEN_SOURCE 
    #include <unistd.h>
    #include <stdio.h>
    
    int main()
    {
        const char *key = "lenovo"; // key 为想要设置的密码
        const char *salt = "xx";	// salt为两字节, 可随意取
    
      char *result = crypt(key, salt);
      printf("password: %s
    ", result);
    
      return 0;
    }

    编译crypt_passwd.cpp

    g++ crypt_passwd.cpp -lcrypt -o crypt_passwd

    输入的xx8FwQtT5iVRQ, 即是lenovo对应加密字符串
    让我们尝试下, 此前的猜测是否正确

    useradd thinkpad -p xx8FwQtT5iVRQ -m -d /home/thinkpad -s /bin/bash
    su thinkpad
    输入密码: lenovo

    现在成功了, oh yeah, 是不是很简单

    那如何为集群添自动添加帐号呢? 可借助上篇免密码登录的方式来实现.

    另一种方式:

    除了在useradd指定-p参数, 也可以借用here document来实现
    编写如下脚本

    #! /bin/bash
    
    # 添加锁定用户
    useradd thinkpad -m -d /home/thinkpad -s /bin/bash
    
    # 借助here document来进行交互, 并设定密码, (两次输入密码是因为passwd需要重复验证)
    passwd thinkpad <<-EOF
      lenovo
      lenovo
    EOF

    使用不指定的密码的useradd, 其创建的帐号是被锁定的, 需要管理员借助passwd对其赋予新密码, 而这边借助here document的方式, 就免去手动输入密码的过程了.

  • 相关阅读:
    ELASTIC 动态修改配置API
    ELASTIC API
    ELASTIC索引监控脚本
    java并发多线程纪要
    Git 基础
    Linux 权限规划ACL
    Linux账号管理(二)
    Linux账号管理(一)
    Linux 备份工具dump
    Linux 文件压缩、打包
  • 原文地址:https://www.cnblogs.com/mumuxinfei/p/3835554.html
Copyright © 2020-2023  润新知