expect是一个免费的编程工具语言,用来实现自动和交互式任务进行通信,而无需人的干预。
系统信息:
NAME="CentOS Linux"
VERSION="7 (Core)"
ID="centos"
ID_LIKE="rhel fedora"
VERSION_ID="7"
PRETTY_NAME="CentOS Linux 7 (Core)"
ANSI_COLOR="0;31"
CPE_NAME="cpe:/o:centos:centos:7"
HOME_URL="https://www.centos.org/"
BUG_REPORT_URL="https://bugs.centos.org/"
CENTOS_MANTISBT_PROJECT="CentOS-7"
CENTOS_MANTISBT_PROJECT_VERSION="7"
REDHAT_SUPPORT_PRODUCT="centos"
REDHAT_SUPPORT_PRODUCT_VERSION="7"
安装expect
yum -y install expect
测试shell脚本,通过ssh登录
#!/bin/bash
password="wei123"
expect <<EOF
set timeout 10
spawn ssh root@192.168.1.105
expect {
"Are you sure you want to continue connecting (yes/no)?" {send "yes\r";exp_continue}
"password:" {send "${password}\r"}
}
expect "]#"
send "exit\r"
expect eof
EOF
exit 0
使用rsync同步文件
安装rsync(客户端和服务器命令相同)
yum -y install rsync
systemctl start rsyncd
systemctl enable rsyncd
shell脚本
#!/bin/bash
doRsync()
{
expect << EOF
set timeout 3600
spawn rsync -azPq $4 $1@$3:$5
expect {
"(yes/no)?" {send "yes\r";exp_continue}
"password:" {send "${password}\r"}
}
expect eof
EOF
}
doRsync "root" "wei123" "192.168.1.105" "/home/export/" "/home/export"
脚本(传参,if):
#!/usr/bin/expect
set option [lindex $argv 0]
if {$option == "1"} {
set url '/data/ops/database'
} elseif {$option == "2"} {
set url '/data/ops/analysis'
} else {
set url '/home'
}
set timeout 3
spawn ssh root@192.168.1.100
expect "*password*"
send "aaaaa\r"
expect "*#"
send "cd $url\r"
interact