Linux expect if then

Using conditional statements inside ‘expect’

Needless to say this doesn’t work, and nor does it look very pretty. From my adventures with Google expect seems to be something of a dark-art. Thanks in advance to anyone for assistance in the matter!

3 Answers 3

Have to recomment the Exploring Expect book for all expect programmers — invaluable.

I’ve rewritten your code: (untested)

proc login  < expect "login:" send "$user\r" expect "password:" send "$pass\r" >set username spongebob set passwords set index 0 spawn telnet 192.168.40.100 login $username [lindex $passwords $index] expect < "login incorrect" < send_user "failed with $username:[lindex $passwords $index]\n" incr index if  < error "ran out of possible passwords" >login $username [lindex $passwords $index] exp_continue > "prompt>" > send_user "success!\n" # . 

exp_continue loops back to the beginning of the expect block — it’s like a «redo» statement.

Note that send_user ends with \n not \r

You don’t have to escape the > character in your prompt: it’s not special for Tcl.

With a bit of bashing I found a solution. Turns out that expect uses a TCL syntax that I’m not at all familiar with:

#!/usr/bin/expect set pass(0) "squarepants" set pass(1) "rhombuspants" set pass(2) "trapezoidpants" set count 0 set prompt "> " spawn telnet 192.168.40.100 expect < "$prompt" < send_user "successfully logged in!\r" >"password:" < send "$pass($count)\r" exp_continue >"login incorrect" < incr count exp_continue >"username:" < send "spongebob\r" exp_continue >> send "command1\r" expect "$prompt" send "command2\r" expect "$prompt" send "exit\r" expect eof exit 

Hopefully this will be useful to others.

I used a similar solution for SSH but read the passwords from a passwords file ‘~/.ssh/ssh-passwords’. The hostname and username is read from my ‘~/.ssh/config’ file. So running: ‘cssh server1’ will expand to ubuntu@server1.mycompany.com

I am new to Expect, the expect < "case1"<. >«case2» <. >«case3»<. >>, is this some kind of switch case statement like C++? thanks

@B.Mr.W. yes, using it in the outside <> basically makes it a fall through instead of individual if statements

If you know the user ids and passwords, then you ought also to know which userid/password pairs are aligned with which systems. I think you’d be better off maintaining a map of which userid/password pair goes with which system then extracting that information and simply use the correct one.

Читайте также:  Все виды linux mint

So — since you obviously don’t like my advice, then I suggest you look at the wikipedia page and implement a procedure that returns 0 if successful and 1 if the expectation times out. That will allow you to detect when the password supplied failed — the prompt expectation times out — and retry. If this is helpful, you can remove your downvote now that I’ve edited it.

In retrospect, you’d probably want to do this in conjunction with the map anyway since you’d want to detect a failed login if the password was changed.

Sorry for the downvote. I was on a long call and wanted a quick way of showing that I didn’t have an answer yet without typing up a post to explain why. Anyway, I certainly wouldn’t be using the conditional method if I had a reliable way of documenting the passwords being used on certain devices. It can change across firmware revisions outside of my control, so all I can do is have a list of passwords ready to try out. I understand what I need to do — use a conditional statement and act on the answer — I just don’t know how to do it. 🙂

You can remove the vote now that I’ve edited — that is if the additional information is helpful or at least doesn’t make the post unhelpful. As long as you don’t accept an answer, people are likely to continue adding answers — though you may want to update your question with the information on why keeping track of the passwords is hard.

Источник

Expect Script Tutorial: Expressions, If Conditions, For Loop, and While Loop Examples

Note: For expect command line arguments, read 6 Expect Script Command Line Argument Examples.

Expect Expressions – expr command

To evaluate the expressions, use the expr command, which executes the given expression and returns the result. Expect expressions are similar to the C expressions. Some of the valid expressions are listed below.

# To add two simple numerical values set sum "[expr 1 + 1]" # To multiple the value of variables set mul "[expr $sum * $sum]" # To evaluate conditions and returns 1 or 0 to indicate success or failure accordingly. set ret "[expr (1+1) == 2]" # Conditions may contain the command return values. set ret [expr [pid] == 0]

Expect Conditional Expressions – If command

If command is used for conditional flow of execution of statements as shown in the example below.

Читайте также:  Просмотр репозитория astra linux

Just like any other programming language, you can use the elseif command in expect as shown below.

Expect Looping Constructs

Expect For Loop Examples:

As we know, for loop is used to do repeated execution of expression until certain condition.

General for loop construct :

Note: You should place the loop open brace in the same line as it contains “for” keyword.

Expect While Loop Examples:

If you enjoyed this article, you might also like..

Comments on this entry are closed.

hi vivek,
I am trying to call a function in a for loop like below:
#!/bin/bash
abc()
/usr/bin/ftp -inv 9 user
get
bye
ENDFTP > for ((i=0; i do
abc
done
the error I am getting is : syntax error: unexpected endof file

Hello, everybody! This is my question
How can I assign a command output to a variable? For example, the result of any ASCII text manipulation, a result of which could be one lines or one word.
Thanks in advance,
israel

@Balak
# To set the variable value which includes output of another command
set proc_id “process id : [pid]” This is wrong, the pid command returns the expect PID: try this and expect will close itself:
[sko@aemaeth:~]$ expect
expect1.1> set pid [pid]
27552
expect1.2> exec kill -15 $pid @Kashyap
you’re not using expect @Israel
set variablename [exec shellcommand], for example: [sko@aemaeth:~]$ expect
expect1.1> set aaa [exec echo “/bin/ls”]
/bin/ls
expect1.2> set b “/tmp/test”
/tmp/test
expect1.3> exec $aaa $b
/tmp/test

This is very good. Can you include an example to open more than one session (e.g. 3 telnet sessions) _simultanesously_ and send/receive text with each session?

hi,
I need 1 help.
I want to search file with current date and with perticular pattern containing some data ie,greter than 0 bytes.and then paste the content of that file. myfile=$(sed -n ‘4,$p’ /tmp/vij/auto/batch_cd.txt) for each in `find /opt/sploutput/RMBP5UAT -mtime 1`
do #echo $each if read each (find . name *$myfile*_*stderr* – size +0c 2>/dev/null)
then
echo “no any log file generated”
ls -lrt
fi
done

Источник

Using if/else in expect script

I think I have a basic grasp of the concept of «if/else» in expect, but I don’t fully understand how to nest them, if there is a better way, or if I’m completely off-base to begin with.

This is what I have right now:

set file1 [open [lindex $argv 0] r] set pw1 [exec cat /home/user/.pw1.txt] set pw2 [exec cat /home/user/.pw2.txt] while <[gets $file1 host] != -1> < puts $host spawn -noecho "ssh $host" expect < "continue connecting"< send "yes\r" expect < "current" < send $pw2\r >"New password" < send $pw1\r >"Retype new password" < send $pw1\r >> expect "msnyder" send "exit\r" > interact > 

The file1 variable is the list of hosts to run the script against.

I know it isn’t accurate because it errors on line 22. But, I have no idea what needs to be fixed.

2 Answers 2

  1. missing close brace, probably for the «continue connecting» block
  2. missing space before the open brace of «continue connecting». Tcl (hence Expect) is very sensitive to whitespace as it is parsed into words before the commands are evaluated. For the very few gory details, see the 12 syntax rules of Tcl.

Your code might look like:

while <[gets $file1 host] != -1> < puts $host spawn -noecho "ssh $host" expect < "continue connecting" < send "yes\r" expect < "current" < send -- $pw2\r exp_continue >"New password" < send -- $pw1\r exp_continue >"Retype new password" < send -- $pw1\r exp_continue >msnyder > send "exit\r" > > interact > 
  • exp_continue is used to «loop» back up to the expect statement: in this case, you will expect to see all of «current», «new» and «retype», so you don’t want to bail out until you see your prompt.
  • get into the habit of typing send — something . Without the double dash, you’ll be surprised the day someone types in a password with a leading dash.

Thank you. I’m looking through the code before I run it so I can get a feel for what it’s doing and how to implement similar methods in the future. One thing that dawned on me is that I now have a couple systems that don’t need the RSA fingerprint to be accepted. Does this script assume it will be asked? If it doesn’t appear and drops straight to the command prompt on the remote server will the block be short-circuited and simply send the «exit» from the msnyder block? Seems like I would just need to move it up one level to be an «else» under the «continue connecting» «if». Is that correct?

Or maybe I need it in two places: once after accepting the RSA fingerprint if presented and once in lieu of the RSA fingerprint if I’ve already accepted it.

I ran the script. I think I’m seeing some changes that can be made to my method, but I»m running into problems with it. I’ll probably consider this issue resolved and open another question with the new problem to keep a separation of issues.

Источник

Оцените статью
Adblock
detector