«

expect 脚本总结

时间:2024-2-21 11:37     作者:韩俊     分类: Linux


expect 脚本总结。

关于一些基础知识和基础示例,可参考:

linux shell之expect 教程

expect实用示例

(1)声明函数和调用函数

proc insertDebianUserIfNo {username password} {
    send "use mysql\r"
    expect "*Database changed*"
    send "select User from user where User='$username';\r"
    expect {
        "*Empty set*" {
            puts "数据库 $username 帐号不存在,尝试创建\n"
            send "create user '$username'@'localhost' identified by '$password';\r"
            expect "*Query OK*"
            send "flush privileges;\r"
            expect "*Query OK*"
            send "grant ALL PRIVILEGES ON *.* to '$username'@'localhost';\r"
            expect "*Query OK*"
            puts "数据库 $username 帐号创建成功\n"
        }
        "*1 row in set*" {}
    }
}

调用示例

insertDebianUserIfNo $username $password

以上是带参数的函数,不带参数如下:

proc insertDebianUserIfNo {} {
    ......
}

调用示例

insertDebianUserIfNo

(2)bash 脚本调用并传参

......
mysql_default_user=`cat /etc/mysql/debian.cnf|grep user|head -n 1|awk '{print $3}'`
mysql_default_pass=`cat /etc/mysql/debian.cnf|grep password|head -n 1|awk '{print $3}'`

/usr/local/bin/init_mysql.expect.sh $mysql_default_user $mysql_default_pass

接受参数的脚本文件 init_mysql.expect.sh 代码片段如下:

#!/usr/bin/expect

set timeout 6

set username [lindex $argv 0] #地一个参数
set password [lindex $argv 1] #地二个参数

puts "username : $username password : $password\n"
......

(3)多分支

......
send "select User from user where User='$username';\r"
expect {
    "*Empty set*" {
        puts "数据库 $username 帐号不存在,尝试创建\n"
        send "create user '$username'@'localhost' identified by '$password';\r"
        expect "*Query OK*"
        send "flush privileges;\r"
        expect "*Query OK*"
        send "grant ALL PRIVILEGES ON *.* to '$username'@'localhost';\r"
        expect "*Query OK*"
        puts "数据库 $username 帐号创建成功\n"
    }
    "*1 row in set*" {} #不做处理
}

标签: linux

热门推荐