在linux操作系统下,使用脚本自动化,一般由两种方案。
方案一:telnet+ftp
方案二:ssh+scp+expect。
以下主要使用ssh+scp+expect为例进行说明使用方式。
第一步:安装expect:yum -y install expect
第二步:验证,执行expect是否正确
第三步:编写脚本ssh_exec(){
ip=$1
user=$2
passwd=$3
cmdstr=$4
/usr/bin/expect <
set time 10
spawn ssh $user@$1
expect {
"*yes/no" { send "yes\r"; exp_continue}
"*password:" {send "$passwd\r"}
}
expect "*#"
expect "*#"
send "$cmdstr\r"
expect "*#"
send "exit\r"
expect eof
EOF
}
function scp_get () {
local ip=$1
local user=$2
local passwd=$3
local src=$4
local dst=$5
[ -z "$ip" -o -z "$passwd" ] && return 1
/usr/bin/expect << EOF
proc remote_exec {ip passwd src dst} {
spawn scp \$user@\$ip:\$src \$dst
exp_internal 0
expect {
"yes/no" { send "yes\\r";exp_continue}
"*password:" {send "\$passwd\\r"}
}
expect eof
}
remote_exec "$ip" "$user" "$passwd" "$src" "$dst"
EOF
}
#从本地服务器复制到远程服务器
function scp_put () {
local ip=$1
local user=$2
local passwd=$3
local localfile=$4
local dst=$5
[ -z "$ip" -o -z "$passwd" ] && return 1
/usr/bin/expect << EOF
proc remote_exec {ip passwd localfile dst} {
spawn scp \$localfile \$user@\$ip:\$dst
exp_internal 0
expect {
"yes/no" { send "yes\\r";exp_continue}
"*password:" {send "\$passwd\\r"}
}
expect eof
}
remote_exec "$ip" "$user" "$passwd" "$localfile" "$dst"
EOF
}
ssh_exec 192.168.1.2 root 111111 'df -h'
scp_get 192.168.1.2 root 111111 '/root/test.txt' '/opt/'
代码说明:
第四步:对脚本授权,执行:chmod -R 755 script.sh
第五步:脚本执行,./script.sh (备注:shell+expect脚本,不能使用sh script.sh执行,只能采用./script.sh执行)