在shell脚本中使用expect实现scp传输问题

1.安装expect

expect用于shell脚本中自动交互,其是基于tcl编程语言的工具。所以安装expect首先安装tcl。本文中使用的是expect5.45tcl8.6.6

安装tcl

[root@tseg0 /]$ mkdir /tools
[root@tseg0 /]$ tar -zxvf tcl8.6.6-src.tar.gz
[root@tseg0 /]$ cd tcl8.6.6/unix/
[root@tseg0 /]$ ./configure
[root@tseg0 /]$ make
[root@tseg0 /]$ make install

安装expect

[root@tseg0 /]$ cd /tools
[root@tseg0 /]$ tar -zxvf expect5.45.tar.gz
[root@tseg0 /]$ cd expect5.45/
[root@tseg0 /]$ ./configure --with-tcl=/usr/local/lib/ --with-tcl include=/tools/tcl8.6.6/generic/
[root@tseg0 /]$ make
[root@tseg0 /]$ make install

shell脚本实现scp传输

命令解释

-c 表示可以在命令行下执行except脚本;
spawn 命令激活一个unix程序来交互,就是在之后要执行的命令;
expect “aaa” 表示程序在等待这个aaa的字符串;
send 向程序发送字符串,expect和send经常是成对出现的,比如当expect“aaa”的时候,send“bbb”。

执行脚本

#! /bin/sh
expect -c "
    spawn scp -r /home/tseg/hello $name@10.103.240.33:/home/$name/
    expect {
        \"*assword\" {set timeout 300; send \"$pass\r\"; exp_continue;}
        \"yes/no\" {send \"yes\r\";}
    }
expect eof"

解释:
第二行: -c 表示可以不用与控制台交互;
第三行:spawn激活一个scp的unix程序;
第五行:expect期待含有“assword”的字符串,设置连接时间最大为300毫秒,如果出现这个字符串,就send 变量pass代表的密码字符串, exp_continue表示执行下面的匹配;
第六航:expect期待含有“assword”的字符串,设置连接时间最大为300毫秒,如果出现这个字符串,就send 变量pass代表的密码字符串;
第八行:表示结束。

  • 2
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值