天天看點

分發系統

第一部分:expect講解

expect可以讓我們實作自動登入遠端機器,并且可以實作自動遠端執行指令。當然若是使用不帶密碼的密鑰驗證同樣可以實作自動登入和自動遠端執行指令。 但當不能使用密鑰驗證的時候,我們就沒有辦法了。是以,這時候隻要知道對方機器的賬号和密碼就可以通過expect腳本實作登入和遠端指令。

使用expect之前,需要先安裝expect:

yum install -y expect

自動遠端登入,并執行指令

首先來看一個登入後不退出的腳本:

#! /usr/bin/expect

set host "192.168.11.102"

set passwd "123456"

spawn ssh  root@$host

expect {

"yes/no" { send "yes\r"; exp_continue}

"assword:" { send "$passwd\r" }

}

interact

 再來看一個登陸後,執行指令然後退出的腳本:

#!/usr/bin/expect

set user "root"

spawn ssh [email protected]

"password:" { send "$passwd\r" }

expect "]*"

send "touch /tmp/12.txt\r"

send "echo 1212 > /tmp/12.txt\r"

send "exit\r"

2. 我們還可以傳遞參數

set user [lindex $argv 0]

set host [lindex $argv 1]

set cm [lindex $argv 2]

spawn ssh $user@$host

"yes/no" { send "yes\r"}

send "$cm\r"

執行: ./2.expect root 192.168.11.18 w

3. 自動同步檔案

spawn rsync -av [email protected]:/tmp/12.txt /tmp/

expect eof

4. 指定host和要同步的檔案

set host [lindex $argv 0]

set file [lindex $argv 1]

spawn rsync -av $file root@$host:$file

執行: ./4.expect 192.168.11.18 /tmp/12.txt

第二部分:建構檔案分發系統

需求背景

對于大公司而言,肯定時不時會有網站或者配置檔案更新,而且使用的機器肯定也是好多台,少則幾台,多則幾十甚至上百台。是以,自動同步檔案是至關重要的。

2. 實作思路

首先要有一台模闆機器,把要分發的檔案準備好,然後隻要使用expect腳本批量把需要同步的檔案分發到目标機器即可。

3. 核心指令

rsync -av --files-from=list.txt  /  root@host:/

4. 檔案分發系統的實作

cat  rsync.expect

spawn rsync -av --files-from=$file / root@$host:/

cat rsync.sh

#!/bin/bash

for ip in `cat ip.list`

do

    echo $ip

    ./rsync.expect $ip list.txt

done

5. 指令批量執行腳本

cat exe.expect

set cm [lindex $argv 1]

spawn ssh root@$host

cat exe.sh

    ./exe.expect $ip "w;free -m;ls /tmp"

本文轉自 15816815732 51CTO部落格,原文連結:http://blog.51cto.com/68686789/1790388

下一篇: LVS基礎配置

繼續閱讀