[英]ssh to different nodes using shell scripting
我正在使用下面的代碼SSH到不同的節點,並查找用戶是否存在。 如果用戶不存在,它將創建它。
如果我不執行ssh腳本可以正常工作,但如果執行ssh則腳本將失敗。
如何使用此腳本瀏覽不同的節點?
for node in `nodes.txt`
usr=root
ssh $usr@$node
do
if [ $(id -u) -eq 0 ]; then
read -p "Enter username : " username
read -s -p "Enter password : " password
egrep "^$username" /etc/passwd >/dev/null
if [ $? -eq 0 ]; then
echo "$username exists!"
exit 1
else
pass=$(perl -e 'print crypt($ARGV[0], "password")' $password)
useradd -m -p $pass $username
[ $? -eq 0 ] && echo "User has been added to system!" || echo "F
ailed to add a user!"
fi
else
echo "Only root may add a user to the system"
exit 2
fi
done
您的腳本存在嚴重的語法錯誤。 我想一開始的for
循環就是您試圖添加的內容,但是您在此過程中完全破壞了腳本。
循環遍歷文件中的行的語法是
while read -r line; do
.... # loop over "$line"
done <nodes.txt
(或者for line in $(cat nodes.txt); do
邊際for line in $(cat nodes.txt); do
...但這有多個問題;有關詳細信息,請參見http://mywiki.wooledge.org/DontReadLinesWithFor )。
如果要在ssh
實際運行腳本的其余部分,則需要將其傳遞給ssh
命令。 像這樣:
while read -r node; do
read -p "Enter user name: " username
read -p -s "Enter password: "
ssh root@"$node" "
# Note addition of -q option and trailing :
egrep -q '^$username:' /etc/passwd ||
useradd -m -p \"\$(perl -e 'print crypt(\$ARGV[0], \"password\")' \"$password\")" '$username'" </dev/null
done <nodes.txt
當然,傳遞給ssh
的命令可能是任意復雜的,但是您將希望避免在具有root特權的遠程腳本中進行交互式I / O,並通常確保遠程命令盡可能安靜且健壯。
反模式command; if [ $? -eq 0 ]; then ...
command; if [ $? -eq 0 ]; then ...
command; if [ $? -eq 0 ]; then ...
很笨拙,但很常見。 if
的目的是運行命令並檢查其結果代碼,因此更好,更慣用的是if command; then ...
if command; then ...
(如果只需要完整的長手if
/ then
/ else
結構的then
或else
部分,則可以更簡潔地編寫command && ...
或! command || ...
)。
也許您應該只通過ssh執行遠程任務。 其余所有在本地運行。
ssh $user@$node egrep "^$username" /etc/passwd >/dev/null
和
ssh $user@$node useradd -m -p $pass $username
如果要在所有節點上創建相同的用戶,則最好在循環外詢問用戶名和密碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.