How to automate telnet session using Expect?

后端 未结 4 1162
一个人的身影
一个人的身影 2020-12-19 06:56

I\'m trying to write an expect script to automate telnet. This is what I have so far.

#!/usr/bin/expect
# Test expect script to telnet.

spawn telnet 10.62.         


        
相关标签:
4条回答
  • 2020-12-19 07:08

    Here is a simplified version

    #!/usr/bin/expect
    # just do a chmod 755 one the script
    # ./YOUR_SCRIPT_NAME.sh $YOUHOST $PORT
    # if you get "Escape character is '^]'" as the output it means got connected otherwise it has failed
    
    set ip [lindex $argv 0]
    set port [lindex $argv 1]
    
    set timeout 5
    spawn telnet $ip $port
    expect "'^]'."
    
    0 讨论(0)
  • 2020-12-19 07:17

    It's hard to tell, but from the output you're pasting it looks like:

    1. Your script isn't waiting for login to complete before sending the next command.
    2. Your script is exiting and closing the process before you can see any output.

    There are no guarantees in life, but I'd try this as a first step:

    #!/usr/bin/expect -f
    
    spawn telnet 10.62.136.252
    expect "foobox login:"
    send "foo1\r"
    expect "Password:"
    send "foo2\r"
    
    # Wait for a prompt. Adjust as needed to match the expected prompt.
    expect "justin>"
    send "echo HELLO WORLD\r"
    
    # Wait 5 seconds before exiting script and closing all processes.
    sleep 5
    

    Alternatives

    If you can't get your script to work by manually programming it, try the autoexpect script that comes with Expect. You can perform your commands manually, and autoexpect will generate an Expect typescript based on those commands, which you can then edit as needed.

    It's a good way to find out what Expect actually sees, especially in cases where the problem is hard to pin down. It's saves me a lot of debugging time over the years, and is definitely worth a try if the solution above doesn't work for you.

    0 讨论(0)
  • 2020-12-19 07:20

    Have you seen this StackOverflow Question?

    He seems to have got things working by using curly braces.

    0 讨论(0)
  • 2020-12-19 07:24

    You're sending the echo command without first expecting the prompt. Try:

    # after sending the password
    expect -re "> ?$"
    send "echo HELLO WORLD\r"
    expect eof
    
    0 讨论(0)
提交回复
热议问题