Search code examples
expect

How to set the Interact timeframe for expect


I am using expect via telnet to connect the box and then using expect script as follows:

expect -c 'spawn -noecho telnet IP' exp_script

On the expect script [exp_script] - Setting the user prompt and then using interact to interact the user to pass their cmd and stay on the prompt for further uses.

However I need to restrict the user to interact with box for certain time, the time frame will be dynamic and changes based on users.

So my question is how to restrict the users to interact the box via expect with certain timeframe only and then user should auto exit from box.

Highly appreciated for any help here!!


Solution

  • This uses the Tcl after command to schedule code to run after X milliseconds

    spawn -noecho telnet IP
    
    proc get_user_time_in_milliseconds {username} {
        # checks here
        set limit 5000   ;# => 5 seconds
        return $limit
    }
    
    proc byebye {spawn_id} {
        send_user "\n\nYour time is up. Bye!\n"
        exp_close $spawn_id
        exit
    }
    
    after [get_user_time_in_milliseconds $env(LOGNAME)] [list byebye $spawn_id]
    
    # rest of expect code goes here.
    interact