linux 脚本 expected,Linux | shell与expect结合使用

在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执行)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值