系统:centos 7
安装tftp-server ,从https://sourceforge.net/projects/empty/?source=navbar下载empty-0.6.19b,(最新版的0.6.20b测试不能使用)
此empty 可以替代expect,且易于编译安装。
按照empty里面的安装说明make && make install
以h3c交换机为例,创建备份配置脚本
vi backuph3cconfig.sh
内容如下:
#!/bin/sh
# emssh.sh v.0.5
# ssh example for empty
# Though, don't really know who wants to use empty for ssh :)
# Copyright (C) 2005, 2006 Mikhail E. Zakharov
#
pkill -9 empty
rm -f /tmp/empty.*
localhostip=`ip a|grep inet|grep -v 127.0.0.1|grep -v inet6|awk '{print $2}'|tr -d "addr:"|cut -d / -f 1`
folder=logs #使用本机的tftp-server时候用,要讲本机的tftp-server的server目录指向这儿
if [ ! -x "$folder" ]; then
mkdir "$folder"
fi
systemctl restart tftp.socket
systemctl restart tftp.service
read -p "Enter tftp server ip:(not input use this host):" tftpinputip
if [ ! -n "$tftpinputip" ]; then #确定tftp-server的IP
tftpip=$localhostip
else
tftpip=$tftpinputip
fi
read -p "Enter connection type--1:telnet 2:ssh(default) please input 1 or 2 :" connectype
if [ ! -n "$connectype" ]; then # 确定连接方式是Telnet还是ssh
connectype=2
else
connectype=$connectype
fi
read -p "Enter switch username:" login #输入交换机用户名
stty -echo
read -p "Enter switch password:" password #不回显输入交换机密码
stty echo
while read ip
do
day=`date +%Y%m%d`
telnet="telnet"
ssh="ssh"# (/full/path/to/)ssh
target="$ip"# target host
fifo_in="/tmp/empty.in"# input fifo
fifo_out="/tmp/empty.out"# output
# -----------------------------------------------------------------------------
telnetcmd="$telnet $target"
sshcmd="$ssh $login@$target"
tmp="/tmp/empty.tmp"# tempfile to store results
echo "Starting empty"
if [ $connectype = 1 ]; then
empty -f -L $tmp -i $fifo_in -o $fifo_out $telnetcmd
else
empty -f -L $tmp -i $fifo_in -o $fifo_out $sshcmd
fi
if [ $connectype != 1 ]; then
sleep 7 #第一次ssh登录时会要弹出保持key的对话框,等待对话框出现
if cat $tmp | grep -q -i "(yes/no)"
then
empty -s -o $fifo_in "yes\n"
fi
fi
if [ $? = 0 ]; then
if [ -w $fifo_in -a -r $fifo_out ]; then
if [ $connectype = 1 ]; then
echo "Sending Username"
empty -w -v -i $fifo_out -o $fifo_in -t 2 sername: "$login\n"
sleep 2
fi
echo "Sending Password"
empty -w -v -i $fifo_out -o $fifo_in -t 2 assword: "$password\n"
empty -w -v -i $fifo_out -o $fifo_in -t 2 \> " \n"
empty -w -v -i $fifo_out -o $fifo_in -t 2 \> "tftp $tftpip put config.cfg config$target-$day.cfg\n" #备份配置文件到tftp-server并重命名
sleep 2
empty -w -v -i $fifo_out -o $fifo_in -t 5 \> "quit\n"
sleep 2
pkill -9 empty
rm -f /tmp/empty.*
else
echo "Error: Can't find I/O fifos!"
return 1
fi
else
echo "Error: Can't start empty in daemon mode"
return 1
fi
echo "Done"
done
创建ip.txt文件,写入要备份交换机的管理IP,一行一个IP
内容示例如下:
192.168.10.10
192.168.10.21
192.168.10.22
执行sh backuph3cconfig.sh 安装提示输入tftp 服务器IP、使用Telnet或者ssh连接、用户名、密码即可批量配备交换机配置
到指定的tftp服务器里。
本脚本h3c交换机测试通过,每分钟可以备份5台交换机的配置文件。