20.28 expect脚本远程登录
内容如下:
#! /usr/bin/expect
set host "192.168.137.130"
set passwd "liang.123"
spawn ssh root@$host
expect {
"yes/no" { send "yes\r"; exp_continue} \r表示回车 exp_continue表示继续
“password:" { send "$passwd\r" }
}
interact 表示 结束,它的作用是停留在远程的机器上,不需要退出来
如果用expect eof 表示远程登陆后会停留1-2秒就会退出来
如果这2个都不用,登陆后就会又马上退出来
给它加上执行权限,再运行脚本,成功远程登陆
20.29 expect脚本远程执行命令
vi 2.expect
#!/usr/bin/expect
set user "root"
set passwd "liang.123"
spawn ssh $user@192.168.137.130
expect {
"yes/no" { send "yes\r"; exp_continue}
"password:" { send "$passwd\r" }
}
expect "]"
send "touch /tmp/12.txt\r"
expect "]"
send "echo 1212 > /tmp/12.txt\r"
expect "]*"
send "exit\r"
给这个脚本添加执行的权限
chmod a+x 2.expect
执行这个脚本,远程登陆了,再执行了2条命令,然后退出来了
执行1.expect 远程登陆后,在/tmp查看是否有12.txt,并cat查看内容
20.30expect脚本传递参数
vi 3.expect
内容
#!/usr/bin/expect
set user [lindex $argv 0] 第一个变量参数的值赋给user
set host [lindex $argv 1] 第一个变量参数的值赋给host
set passwd "liang.123"
set cm [lindex $argv 2] 第三个参数cm
spawn ssh $user@$host
expect {
"yes/no" { send "yes\r"}
"password:" { send "$passwd\r" }
}
expect "]"
send "$cm\r"
expect "]"
send "exit\r"
添加权限
chmod a+x 3.expect
执行脚本,并输入3个参数 首先要登陆到远程的机器,再执行命令
执行多个命令
27 分发系统介绍 expect脚本远程登录 expect脚本远程执行命令 expect脚本传递参数
原文地址:http://blog.51cto.com/13450039/2107858