Jump to content
em

[linux] Expect

Recommended Posts

Scriu acest mini-tutorial ca s? v? deschid apetitul pentru acest limbaj de scripting de nivel înalt.

Cum îl instalez?

# apt-get install expect

Ce po?i face cu el?

Diferite automatiz?ri pentru programe CLI / testare de corectitudine pentru programe scrise de voi.

Exemple

* Hello World


#!/usr/bin/expect
expect "hello"
send "world"

Asteptari:

Va scrie hello pe ecran si asteapta "world" scris de voi. Nu se opreste pana nu scrieti.

Poate v? gândi?i "cât timp a?tept??". Cât vre?i voi. 10 secunde de exemplu.


#!/usr/bin/expect
[b]set timeout 10[/b]
expect "hello"
send "world"

* Vreau un script care s? încerce s? se conecteze prin ssh la un server prin parametrii primi?i de la linia de comand? ?i s? îmi p?streze conexiunea doar dac? serverul are o anumita versiune de kernel.



#!/usr/bin/expect
set timeout 5

set ip [lindex $argv 0]
set user [lindex $argv 1]
set password [lindex $argv 2]

spawn ssh "$user\@$ip"
expect {
"*yes/no*"
{
send "yes\r"
expect "*password:"
send "$password\r"
}
"*password:"
{
send "$password\r"
}
}
expect "$user\@"
send "uname -r\r"
expect {
"2.6.18*"
{
interact
}
"2.*"
{
exit
}
}

Testare: ./test.exp 127.0.0.127 root parolaem

Aici a?i mai înv??at c? suport? ?i parametrii în linia de comand? + regex. Din codul ?sta poate fi f?cut un proiect interesant (de exemplu poate fi scris astfel încât s? trag? diverse exploituri pentru diverse versiuni de kernel ?i s? vad? dac? poate lua root).

* Un snippet care imi descarc? toate fi?ierele de pe un server ftp.


..
expect "username:"
send "$my_user_id\r"
expect "password:"
send "$my_password\r"
expect "ftp>"
send "bin\r"
expect "ftp>"
send "prompt\r"
expect "ftp>"
send "mget *\r"
expect "ftp>"
send "bye\r"
expect eof
..

Concluzie

Expect este un utilitar foarte bun acolo unde avem programe CLI dar nu avem puterea de a scrie scripturi.

Alte resurse:

- man expect

- Expect - Wikipedia, the free encyclopedia

- 6 Expect Script Examples to Expect the Unexpected (With Hello World)

  • Upvote 1
Link to comment
Share on other sites

@Zatarra

Corect. Dar în general mul?imea de output-uri e finit? (îl po?i pune s? fac? matching ?i pe * într-un case, un fel de caz default în care s? faci ceva dac? ai output necunoscut). Nu e bun pentru orice, dar e bine ca to?i s? ?tie c? exist?.

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.



×
×
  • Create New...