[英]Passing a pre-defined variable from shell script to shell script in Linux
[英]Write script to create multiple users with pre-defined passwords
所以我想制作一個腳本,從運行的 users.txt 創建用戶
useradd -m -s /bin/false users_in_the_users.txt
並在passwords.txt中填寫密碼兩次(以確認密碼)
這是腳本
#!/bin/bash
# Assign file descriptors to users and passwords files
exec 3< users.txt
exec 4< passwords.txt
exec 5< passwords.txt
# Read user and password
while read iuser <&3 && read ipasswd <&4 ; do
# Just print this for debugging
printf "\tCreating user: %s with password: %s\n" $iuser $ipasswd
# Create the user with adduser (you can add whichever option you like)
useradd -m -s /bin/false $iuser
# Assign the password to the user, passwd must read it from stdin
passwd $iuser
done
問題是,它沒有填寫密碼。 還有一件事,我希望腳本填寫兩次密碼。
有什么建議?
您必須在標准輸入上提供密碼。 代替:
passwd $iuser
和:
passwd "$iuser" <<<"$ipasswd
$ipasswd"
或者,按照 mklement0 的建議:
passwd "$iuser" <<<"$ipasswd"$'\n'"$ipasswd"
咒語<<<
創建了一個here-string 。 <<<
的字符串作為標准提供給<<<
之前的命令。 在這種情況下,我們提供passwd
命令所需的密碼的兩個副本。
(腳本從純文本文件中讀取這些密碼。我假設您的情況是一些特殊情況,這不像通常那樣危險。)
John1024 的答案是正確的- 他關於從純文本文件中讀取密碼的警告值得重復。
讓我在上下文中展示解決方案,沒有文件描述符雜技( exec 3<
, ...):
#!/bin/bash
# NOTE: Be sure to run this script with `sudo`.
# Read user and password
while read iuser ipasswd; do
# Just print this for debugging.
printf "\tCreating user: %s with password: %s\n" $iuser $ipasswd
# Create the user with adduser (you can add whichever option you like).
useradd -m -s /bin/false $iuser
# Assign the password to the user.
# Password is passed via stdin, *twice* (for confirmation).
passwd $iuser <<< "$ipasswd"$'\n'"$ipasswd"
done < <(paste users.txt passwords.txt)
paste users.txt passwords.txt
讀取對應從兩個文件,並將它們放在一單行線,具有分離\\t
。<(...)
)通過管道傳輸到標准輸入。read
從單個源讀取。$\\n
是一個ANSI C 引用的字符串,它產生一個(文字)換行符。 #! /bin/bash
for i in {1..100}
do
`sudo mkdir -p /root/Desktop/userm$i`
`sudo useradd -m -d /root/Desktop/userm$i -s /bin/bash userm$i`
echo "userm$i:userm$i" | chpasswd
done
這將創建 100 個用戶。
用戶名將是 (userm1-userm100)。
主目錄將是 /root/Desktop/(userm1-user100)
密碼將是 (userm1-userm100)
而不是使用這一行:
useradd -m -s /bin/false $iuser
試試這個:
useradd -m -s /bin/false -p $ipasswd $iuser
你實際上並不需要這個:
passwd $iuser <<< "$ipasswd"$'\n'"$ipasswd"
以下是使用Python腳本的方法,您可以按如下方式運行:
root@ubuntu:/# python multiUser.py user_password.txt
閱讀vichhaiy的博客使用Python腳本在Linux中創建多個用戶,以獲取有關muliUser.py
和user_password.txt
詳細信息。
請運行以下腳本。
#!/bin/bash
#purpose: bash script to create multiple users with pre-defined passwords at once.
#Read_Me: The import file should be in two columns, first users name and second passwords.
#author: Bablish Jaiswal
#contact: linux.cnf@gmail.com
read -p "Kindly import/type Users Name-password file with location:- " creation_info
cat $creation_info |while read i p
do
( useradd $i && echo -e "${p}\n${p}" | passwd $i ) > /dev/null 2>&1 && echo $user ${i} created and password is ${p} || echo ${i} failed
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.