shell 脚本实战笔记(9)--linux自动批量添加用户
前言:
添加linux用户帐号,这个相对简单, 在面对集群, 许多机器的时候, 我们该如何去做和实现? 这篇短文, 简单讲解一些思路, 尽可能地涉及周边的一些知识点. 不光是运维人员会面临这个问题, 对一个基于linux平台的集群服务或软件(比如hadoop集群), 有时也会涉及到这块.
应用场景:
是以centos 6.4作为演示的系统, 其他的系统有类同, 也有差异, 且以实战演练, 一步步的讲述下流程.
*) 实战演练
查阅useradd的使用和参数选项
useradd --help
1 2 3 4 | -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
1 2 | -p, --passwordPASSWORD 加密了的密码,就像 crypt( 3 ) 的返回值。默认为禁用密码。 |
crypt是个系统函数, 我们继续查阅
man 3 crypt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | #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\n" , 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来实现
编写如下脚本
1 2 3 4 5 6 7 8 9 10 | #! /bin/bash # 添加锁定用户 useradd thinkpad -m -d /home/thinkpad -s /bin/bash # 借助here document来进行交互, 并设定密码, (两次输入密码是因为passwd需要重复验证) passwd thinkpad <<-EOF lenovo lenovo EOF |
使用不指定的密码的useradd, 其创建的帐号是被锁定的, 需要管理员借助passwd对其赋予新密码, 而这边借助here document的方式, 就免去手动输入密码的过程了.
posted on 2014-07-10 15:02 mumuxinfei 阅读(2409) 评论(0) 编辑 收藏 举报
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构