linux shell脚本嵌入一段expect
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了linux shell脚本嵌入一段expect相关的知识,希望对你有一定的参考价值。
手头上有非常多的linux机器需要收集log,每个机器上跑相同的脚本,然后全部收集到一台。不通过文件服务器,只能通过scp复制。脚本如下
#!/bin/bash
ip_last="这是一段取出脚本运行所在机器的IP最后一位"
dmesg >>/$home/Test_log/dmesg_$ip_last.log
cat /var/log/message >>/$home/test_log/messag_$ip_last.log
.....省略部分与以上类似,都是收集log,l保存到指定路径。每个log文件名字都以ip_last结尾。
expect -c "
spawn scp /$home/Test_log/*.log root@192.168.1.2:/root/Desktop/test_log/
expect "password:"
send "111111\r"
send "exit\r"
"
保存后,执行,执行到expect -c后就执行不了了,第一句spawn就无法执行。确定expect tcl是安装好了的。因为如果纯expect脚本的话,是没问题的。
不懂expect如何使用, 就一起研究一下? 参考技术B expect -c 用全路径?比如 /usr/bin/expect -c
linux通过shell脚本实现telnet交互式自动化
首先需要有expect:
可以通过以下命令查看是否安装,如果未安装直接 yum install expect,如果不行请自行百度安装。
[root@localhost home]# whereis expect
expect: /usr/bin/expect /usr/share/man/man1/expect.1.gz
[root@localhost home]# expect
编写脚本如下:
#!/bin/bash
passwd="123456"
/usr/bin/expect <<-EOF
set timeout 50
spawn ssh root@10.10.22.38
expect
"*yes/*" send "yes\\r"; exp_continue
"*password:" send "$passwd\\r"
expect "*]*"
send "df -h\\r"
EOF
解释一下:
/usr/bin/expect <<-EOF #开始用expcet执行标志
EOF #结束标志
expect #是expect要实现交互的命令集
[root@localhost home]# ssh root@10.10.22.38
"*yes/*"
"*password:" send "$passwd\\r" #如上如果遇到返回值 *代表无限字符,后面是password:则执行 send发送字符串 \\r回车
expect "*]*" #等待出现]执行下一条命令
send "df -h\\r" #执行命令并回车。
#!/bin/bash
passwd="admin"
/usr/bin/expect <<-EOF
set timeout 50
spawn telnet 0
expect
"Login*" send "admin\\r"
expect
"*assword:" send "$passwd\\r"
expect
"*admin>" send "security enable protocol-detect\\r"
expect
"*admin>" send "security set port-abnormal detect 2\\r"
expect
"*admin>" send "security show protocol-detect status\\r"
expect
"*admin>" send "security show port-abnormal-detect level\\r"
expect
"*admin>" send "exit\\r"
EOF
以上是关于linux shell脚本嵌入一段expect的主要内容,如果未能解决你的问题,请参考以下文章
windows shell脚本命令中,暂停一段时间用哪个命令?