ssh通過公鑰實現身份認證,可以手工創建.ssh目錄並將公鑰拷貝至遠程主機。
也可通過ssh-copy-id命令將公鑰傳遞至遠程主機。
對於批量化部署:
1首先要解決的是身份認證的問題(root密碼應該統一)。
2然後通過sshpass的-p密碼或-f指定密碼文件的方式來傳遞密碼,實現認證登錄。
3通過sshpass配合ssh-copy-id命令執行公鑰傳遞
腳本實現公鑰的批量分發:
1 sshpass的安裝
下載sshpass-1.06
解壓並安裝
tar zxvf sshpass-1.06
./configure
make&&make install
2腳本
#!/bin/bash
. /etc/init.d/functions
usage () {
if [ ! $# -eq 2 ];then
echo "Usage:/bin/sh $0 -f host_list_file"
exit 0
fi
}
auth () {
ID=`id|awk -F"[=()]+" '{print$2}'`
if [ $ID -ne 0 ];then
echo "This tool should be running under root. Exit."
exit 0
fi
}
pubkey () {
#Create ssh_key
if [ ! -f ~/.ssh/id_dsa ];then
echo "The ssh key is not exist. It will be created..."
echo -e "\n"|ssh-keygen -t dsa -N "" >/dev/null2>&1
echo "The key is created successful."
fi
#Disable StrictHostKeyChecking
grep "^StrictHostKeyChecking no"/etc/ssh/ssh_config >/dev/null 2>&1
if [ $? -ne 0 ];then
echo "StrictHostKeyChecking no" >> /etc/ssh/ssh_config&>/dev/null
fi
}
deploy () {
#input root and password
echo "Deploying pub key."
read -p "Please type the remoteaccount:" ac
read -s -p "Please type the remotepassword:" pw
echo
#Deploy pub key
if [ -f $Hosts ];then
for n in `cat $Hosts`
do
sshpass -p $pw ssh-copy-id -i .ssh/id_dsa.pub $ac@$n &>/dev/null
if [ $? -eq 0 ];then
action "Deploying pub_key for $n......Success!" /bin/true
else
action "Deploying pub_key for $n......Failed!" /bin/false
fi
done
else
exit 0
fi
}
usage $1 $2
Hosts="$2"
auth
pubkey
deploy
3測試
創建主機列表文件hosts
cat /root/hosts
192.168.1.104
192.168.1.105
執行腳本sh deploy_pubkey.sh -f host
然後就可以通過ssh/sshpass/pssh等工具進行遠程管理了。