搭建CDH批量执行的脚本

0.前言

在搭建cdh的过程中,需要执行大量相同的命令到不同的机器,因此编写批量脚本。

0.1 注意点

node.list内为所有节点IP
需要下载expect
根据实际情况修改脚本中的密码

1.批量执行命令的脚本如下:

1.1 batch_cmd.sh

#!/bin/sh
list_file=$1
cmd=$2
username=root
password=password
cat $list_file | while read line
do
   host_ip=`echo $line | awk '{print $1}'`
   #username=`echo $line | awk '{print $2}'`
   #password=`echo $line | awk '{print $3}'`
   ./expect_cmd $host_ip $username $password "$cmd"
done

1.2 expect_cmd

#!/usr/bin/expect
set timeout 10
set host [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set cmd [lindex $argv 3]
spawn ssh -p 22 $username@$host "$cmd"
expect {
  "(yes/no)?"
  {
   send "yes\n"
   expect "*assword:" { send "$password\n"}
  }
  "*assword:"
  {
   send "$password\n"
  }
}
expect "100%"
#expect eof
exit 0

2.批量传输的脚本如下:

2.1 batch_scp.sh

#!/bin/sh
list_file=$1
src_file=$2
dest_file=$3
username=root
password=password
cat $list_file | while read line
do
   host_ip=`echo $line | awk '{print $1}'`
   #username=`echo $line | awk '{print $2}'`
   #password=`echo $line | awk '{print $3}'`
   ./expect_scp $host_ip $username $password $src_file $dest_file
done

2.2 expect_scp

#!/usr/bin/expect
set timeout 10
set host [lindex $argv 0]
set username [lindex $argv 1]
set password [lindex $argv 2]
set src_file [lindex $argv 3]
set dest_file [lindex $argv 4]
spawn scp -r $src_file $username@$host:$dest_file
expect {
 "(yes/no)?"
 {
  send "yes\n"
  expect "*assword:" { send "$password\n"}
 }
 "*assword:"
 {
  send "$password\n"
 }
}
expect "100%"
expect eof

3.使用案例

3.1 批量传输的脚本

sh batch_scp.sh node.list /etc/profile /etc

3.2 批量执行命令

sh batch_cmd.sh node.list "source /etc/profile"
上一篇:安装MySQL


下一篇:java基础回顾(一)