shell编程expect用法

shell编程expect用法shell 脚本需要交互的地方可以使用 here 文档是实现 但是有些命令却需要用户手动去就交互如 passwd scp 对自动部署免去用户交互很痛苦 expect 能很好的解决这类问题 expect 的核心是 spawnexpects 调用要执行的命令 expect 等待命令提示信息的出现 也就是捕捉用户输入的提示 send 发送需要交互的值 替代了用户手动输入

shell脚本需要交互的地方可以使用here文档是实现,但是有些命令却需要用户手动去就交互如passwd、scp

对自动部署免去用户交互很痛苦,expect能很好的解决这类问题。

expect的核心是spawn expect send set

spawn 调用要执行的命令

expect脚本必须以interact或expect eof结束,执行自动化任务通常expect eof就够了。

expect编写语法,expect使用的是tcl语法。

反斜线符号是用来引用特殊符号. 例如:n 代表换行. 反斜线符号也被用来关闭”$”符号, 引号,方括号和大括号的特殊含义

expect使用实例

1。首先确认expect的包要安置。

#rpm -qa | grep expect

如果没有则需要下载安装,

#yum install expect

2.安装完成后,查看expect的路径,可以用

#which expect

/usr/bin/expect

 

#!/usr/bin/expect  -f   //这个expect的路径就是用which expect 查看的结果

 

spawn su – nginx       //切换用户

expect “password:”      //提示让输入密码

send “testr”       //输入nginx的密码

interact                //操作完成

 

4.确定脚本有可执行权限

chmod +x autosu.sh

5.执行脚本 expect autosu.sh 或 ./autosu.sh

expect常用脚本

登陆到远程服务器

 

#!/usr/bin/expect  

set timeout 5

set server [lindex $argv 0]

set user [lindex $argv 1]

set passwd [lindex $argv 2]

spawn ssh -l $user $server

expect {

“(yes/no)” { send “yesr”; exp_continue }

“password:” { send “$passwdr” }

}

expect “*Last login*” interact

 

scp拷贝文件

#!/usr/bin/expect

set timeout 10

set host [lindex $argv 0]        //第1个参数,其它2,3,4参数类似

set username [lindex $argv 1]

set password [lindex $argv 2]

set src_file [lindex $argv 3]

set dest_file [lindex $argv 4]

spawn scp $src_file $username@$host:$dest_file

expect {

“(yes/no)?”

   {

    send “yesn”

    expect “*assword:” { send “$passwordn”}

}

“*assword:”

{

send “$passwordn”

}

}

expect “100%”

expect eof

done

 

 

 

 

 

 

 

 

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/216094.html原文链接:https://javaforall.net

(0)
上一篇 2026年3月18日 下午12:34
下一篇 2026年3月18日 下午12:34


相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号