expect学习

来源:互联网 发布:sdn软件定义网络 编辑:程序博客网 时间:2024/05/15 04:55

自动登录远程机器,执行相关命令。

expect_exec.sh

#!/usr/bin/expect -flog_file expect_exec.logset timeout 5set ip [lindex $argv 0]set user [lindex $argv 1]set password [lindex $argv 2]set cmd_str [lindex $argv 3]spawn ssh $user@$ipexpect {"(yes/no)" { send "yes\r"; exp_continue}"Permission denied" { send_user "error:${expect_out(buffer)}\n"; exit 1}"assword:" { send "${password}\r"; exp_continue}"${user}" {send "${cmd_str} \r";send "exit \r";exp_continue }timeout { send_user "timeout $user@$ip\n"; exit 1 }"logout" { exit}}exit 0

使用示例:

#!/bin/shIP_INFO=(#ip|username|passwd   "192.168.80.128|cq|cq"   "192.168.80.128|cq|cq")CMD_STR="touch aa.txt; echo 'haha' >>aa.txt;"for ip_info in ${IP_INFO[@]};do    echo $ip_info    ip=$( echo $ip_info | awk -F "|" '{print $1}')    user=$( echo $ip_info | awk -F "|" '{print $2}')    password=$( echo $ip_info | awk -F "|" '{print $3}')    ./expect_exec.sh $ip $user $password "$CMD_STR"done



0 0