判斷的方式批量創建用戶和密碼(非交互式)

需求

此腳本能夠實現創建本地用戶,腳並且這些用戶的用戶名來自一個包含用戶名列表的文 件,同時滿足下列要求:
此腳本要求提供一個參數,此參數就是包含用戶名列表的文件
如果沒有提供參數,此腳本應該給出下面提示信息Usage: /root/batchusers userfile,並且退出返回相應的值 ,如果提供一個不存在的文件名,此腳本應該給出下面的提示信息 Input file not found然後退出並返回相應的值
創建的用戶shell/bin/false
密碼爲:123

說明

這個腳本是在本機上運行的,不是交互式,我shell分類中有說過交互式的使用方式,也可以結合交互式腳本使用批量爲其他服務器批量創建用戶名。

方法一

下面重要參數說明:
$#:執行腳本後面是否有輸入參數
-f $1:-f是判斷文件,$1是第一次參數
exit:後面的數字可不加,是爲了方便查看這是第幾個exit,但下面位置的exit必須要加,否則腳本不能按預期運行。


[root@server0 ~]# cat q
c1
c2
c3
[root@server0 ~]# 
[root@server0 ~]# cat /etc/foo.sh 
#!/bin/bash

if [ $# -eq 0 ] ;then
	echo "Usage: /root/batchusers userfile"
	exit 1
fi
if [ -f  $1 ] ;then
 	for userlist in `cat $1` ;do
	useradd -s /bin/false $userlist
	echo 
	done
else
		echo "Input file not found"	
fi

root@server0 ~]# chmod +x /etc/foo.sh
[root@server0 ~]# sh /etc/foo.sh 
Usage: /root/batchusers userfile
[root@server0 ~]# sh /etc/foo.sh a
Input file not found
[root@server0 ~]# sh /etc/foo.sh a3
Input file not found
[root@server0 ~]# 
[root@server0 ~]# sh /etc/foo.sh q
Changing password for user c1.
passwd: all authentication tokens updated successfully.
Changing password for user c2.
passwd: all authentication tokens updated successfully.
Changing password for user c3.
passwd: all authentication tokens updated successfully.
[root@server0 ~]# 

方式二

下面重要參數說明:
$#:執行腳本後面是否有輸入參數
-f $1:-f是判斷文件,$1是第一次參數
exit:後面的數字可不加,是爲了方便查看這是第幾個exit,但下面位置的exit必須要加,否則腳本不能按預期運行。

[root@server0 ~]# cat w
ccx1
ccx2
ccx3
[root@server0 ~]# cat /etc/batchusres 
#!/bin/bash

if [ $# -eq 1 ] ;then
	if [ -f $1 ] ;then
		for  username in `cat $1`;do
		useradd -s /bin/false $username
		echo "123" | passwd --stdin $username
		done
	else
		echo "Input file not found"
		exit 1
	fi
else
	echo "Userge:/Userge: /root/batchusers userfile"
	exit 2
fi	
[root@server0 ~]# chmod +x /etc/batchusres
[root@server0 ~]# sh /etc/batchusres ^C
[root@server0 ~]# sh /etc/batchusres 
Userge:/Userge: /root/batchusers userfile
[root@server0 ~]# sh /etc/batchusres  b
Input file not found
[root@server0 ~]# sh /etc/batchusres  2
Input file not found
[root@server0 ~]# sh /etc/batchusres w
Changing password for user ccx1.
passwd: all authentication tokens updated successfully.
Changing password for user ccx2.
passwd: all authentication tokens updated successfully.
Changing password for user ccx3.
passwd: all authentication tokens updated successfully.
[root@server0 ~]# 
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章