天天看點

expect

expect工具:

應用于自動化互動式操作的場景,借助expect處理互動的

                              指令,可以将互動過程寫在一個腳本上使之自動化完成,

                                适用于多台伺服器執行相同操作的環境。            
expect [選項] [-c cmds]  [  [ - [ f | b]  ]  cmdfile  ]  [ args ]           
-c:從指令行執行expect腳本,預設expect是互動地執行的

                     示例:expect  -c  'expect  "\n"  {send  "pressed  enter\n"}'

                     -d:  可以輸出調試資訊

                     eg:expect  -d  ssh.exp

                     expect 中相關指令

                     spawn:啟動新的程序;監控互動式,并且激活。

                     send:用于向程序發送字元串、

                     expect:從程序接收字元串

                     interact:允許使用者互動

                     exp_continue  比對多個字元串在執行動作後加此指令

                     expect eof:表示退出

                     #!/bin/bash

                     spawn  scp /etc/fatab  [email protected]:/data
                     expect  {
                     "yes/no"  {send "yes\n";exp_continue}
                     "password"  {send  "magedu\n"}

                     }
                     expect  eof

                     #!/usr/bin/expect

                     set  ip  [lindex  $argv  0]

                     set  user  [lindex  $argv  1]

                     set  password  [lindex  $argv 2]

                     spawn  ssh  $user@$ip

                     expect{

                              "yse/no" { send  "yes\n";exp_continue }

                                        "password" { send "redhat }

                     }
         interact           
#!/usr/bin/expect

        set ip [lindex $argv 0]

        set user [lindex $argv 1]

        set password [lindex $argv 2]

        set timeout  10

        spawn  ssh $user@$ip

        expect {

                   "yes/no" { send "yse\n;exp_continue" }

                             "password" { send "$password\n"}

        }

        expect  "]#"  { send "useradd haha\n"}

        expect "]#" {send "echo magedu |passwd  --stdin haha\n"}

        send  "exit\n"

        expect eof

        #!/bin/bash

        ip=$1

        user=$2

        password=$3

        expect  << EOF

        set  timeout  10

        spawn  ssh  $user@$ip

        expect {

                    "yes/no" { send  "yes\n; exp_continue" }

                                "password"  { send  "passwor\n" }
        }

        expect  "]#"  { send  "useradd  haha\n" }

        expect  "]#"  { send  "echo  redhat |passwd  --stdin  haha\n" }

        expect  eof

        EOF

    注意:expect 中 {}内,不必擔心與{是否有空格,這個沒有影響的。           

繼續閱讀