
我有下面的 bash 腳本,每次我想創建一個用戶時,我都需要將此腳本複製到伺服器並運行它。
我們可以做些什麼來讓這個腳本從hosts.txt檔案(在多個伺服器上執行腳本)中逐一取得IP並在伺服器上建立使用者。
1.詢問一次密碼,並在腳本的其餘部分(如有必要)中使用它。 2.以普通用戶身分登入。 3.成為root用戶並運行腳本
#!/bin/bash
#Script to Add User
read -p 'Please Enter The Username To Add: ' name
echo "$name" > /tmp/userlist.txt
clear
echo -e "Hallo $name\nYour Name Is Added To The List."
userfile=/tmp/userlist.txt
username=$(cat /tmp/userlist.txt | tr 'A-Z' 'a-z')
for user in $username
do
useradd $user -N -s /bin/bash
usermod -aG sudo $user
passwd $user
done
echo "=================================="
echo "User $name Have Been Created."
echo "=================================="
tail /etc/passwd | cut -d: -f1
答案1
如果您想複製腳本並從集中點運行它,請建立負責複製和執行的通用配置腳本
建立一個陣列列表,在本例中我使用了一個名為 hostList.active 的文件
將唯一的參數設定為您嘗試在遠端伺服器上複製和執行的腳本。 (在這種情況下,它將在遠端電腦的主目錄中運行)
#! /bin/bash while read box; do ping -c 1 -w 1 -q $box > /dev/null if (test $? = 0); then echo "***************************************************************" echo $box scp $1 $box:~/. ssh -n -o stricthostkeychecking=no -X $box "~/$1" else echo $box is not responding to ping echo $box >> hostList.notdone fi done < hostList.active
我在數組列表檔案 (hostList.active) 中放置了 2 個測試伺服器,它連接到這兩個伺服器,複製腳本並執行它。
./copyandrun.sh bogus.sh
***************************************************************
tsweb
bogus.sh 100% 36 0.0KB/s 00:00
Running a Test
***************************************************************
tsdb
bogus.sh 100% 36 0.0KB/s 00:00
Running a Test
確保您複製的腳本具有適當的權限,以便能夠由您複製的任何使用者執行。