shell分发公钥到目标服务器,实现免密登录
搭集群,如果手动分发公钥到各个节点那是真的类,得想办法弄个脚本帮忙才行,花了不少时间整一个能跑的脚本真不容易/(ㄒoㄒ)/~ 虽然写的烂但起码能是实现了功能,哈~~
#!/usr/bin/expect
set curAgent [lindex $argv 0]
set serverIp [lindex $argv 1 ]
set user_name "root"
set password "cheng"
set timeout 4
spawn ssh $user_name@$curAgent
expect {
"*yes/no" {
send "yes\r"; exp_continue}
"*password:" {
send "$password\r"}
"*login*" {
exit }
}
expect "#"
send "cd .ssh\r"
expect {
"*directory*" {
send "mkdir .ssh;chmod 700 .ssh;cd .ssh;\r";exp_continue}
"#" {
send "scp $user_name@$serverIp:/root/.ssh/id_rsa.pub /root/.ssh/id_rsa.pub_ambariserver\r "}
}
expect {
"*yes/no" {
send "yes\r"; exp_continue}
"*password:" {
send "$password\r"}
}
expect "#"
send "cat authorized_keys \r"
expect {
"*directory*" {
send "cat id_rsa.pub_ambariserver >> authorized_keys;rm -f id_rsa.pub_ambariserver\r"}
"#" {
send "cat id_rsa.pub_ambariserver >> authorized_keys;rm -f id_rsa.pub_ambariserver\r"}
}
expect eof
将所有agent写到server端的hosts文件下。
#!bash/bin
hosts=(
"192.168.10.1|bigdata001.qjc.com|bigdata001"
"192.168.10.3|bigdata003.qjc.com|bigdata003"
"192.168.10.4|bigdata004.qjc.com|bigdata004"
)
fileReplaced=/etc/hosts
findStr=bigdata
getDelLines()
{
lineNums=$(sed -n -e "/$findStr/=" $fileReplaced)
for lineNum in ${lineNums[*]}
do
delLines="$delLines;$lineNum d"
done
echo $delLines
}
writeHost2FileReplaced(){
for curHost in ${hosts[*]}
do
echo `echo $curHost|sed 's/|/\t/g'` >>$fileReplaced
done
}
result=$(getDelLines)
$(sed -i "${result:1:${#result}}" $fileReplaced)
writeHost2FileReplaced
批量分发
#bin/bash
hostnames=(
bigdata004
bigdata001
)
for host in ${hostnames[*]}
do
echo "$host 开始分发">>resultIP
expect -f master_login_slave.sh $host 192.168.10.3
echo "$host 完成分发">>resultIP
done