为了方便的从多台服务器获取日志,写了个简易脚本专门用于批量拷贝服务器日志到执行脚本的机器中。该脚本包含2个文件bscp.sh和bscp.exp。
使用方式:
sh bscp.sh <username> <host1,host2> <log_file>
username:你ssh到目标机器的密码。 host1,host2:目标机器的ip或者机器名,多个之间用逗号分割。 log_file:你要批量下载的日志的绝对路径。运行后,程序提示输入目标机器的密码(这里需要多台机器的ssh用户名密码是相同的,且之前需要建立过ssh连接,就是不需要再进行yes/no交互)
bscp.sh主程序:
#!/bin/bashif [ $# != 3 ] ;then echo "usage:" exit 1fistty -echo #隐藏密码输出read -p "Please enter target hosts' passwd of $1:" passwdstty echoechodirpath=`dirname $0`#echo $dirpath$dirpath/bscp.exp $1 $2 $3 $passwd
expect脚本:
#!/usr/bin/expect -fset user [lindex $argv 0]set hosts [lindex $argv 1]set logfile [lindex $argv 2]set passwd [lindex $argv 3]set timeout 10set hostlist [split $hosts ","] # 把host字符串分割成列表set slashIdx [expr [string last / $logfile] + 1] set filename [string range $logfile $slashIdx end] # 获取日志文件名foreach h $hostlist { set hostfile $filename spawn scp $user@$h:$logfile ./$filename.$h expect "*Enter passphrase for key*" { # 这里可以改成其他可能出现的显示文字,如password:等.或者加多yes/no的交互环节 send "$passwd\r" send "\r" } expect "*%*" {set timeout -1 ; puts "\rtrasmitting..."} expect eof { # 下载完成后输出成功信息 puts "\rtransmit successfully!" set timeout 10 }}
一个栗子:
执行获取3台机日志:
./bscp.sh ultrani host1,host2,host3 /home/admin/xxx/logs/access.log结果是把3台机器的日志下载到执行脚本的目录中
日志后缀以机器名结尾:
access.log.host1 access.log.host2 access.log.host3