Question

I'm writing a library to support telnet'ing to a remote server and running apps.

Things are going swimmingly in establishing a connection, getting data back, parsing, etc. (at least as swimmingly as it can be for communicating with programs via a text interface).

One app will change the cursor if it enters properly, or leave the original cursor if it fails (I don't write the apps, I just have to use them.)

When said app starts up correctly, this works with no problem:

promptB = "hello(x)# "   # Yes, the space at the end is intentional
response = tn_conn.cmd("app_name\n", prompt=promptB)

I would like to use the prompt change (or lack of prompt change) to detect whether the program failed to start. I figured this would be a golden opportunity to try telnetlib's expect(), since expect() allows one to pass a list of strings to match in the response.

I cannot, however, get this to work:

promptA = "hello(x)# "   # Yes, the space at the end is intentional
promptB = "hello> "      # Yes, the space at the end is intentional

tn_conn.write("app_name\n")
which_prompt, mo, response = self.tn_conn.expect([promptA, promptB], timeout=3)

The expect command always times out, whether to apps starts sucessfully or not.

which = "-1"

mo = None

response = "mumble mumble\r\r\n other stuff\r\n\r\nhello# "

The docs say that either a string or a regex object can be passed to expect (I'm passing a string), so am I missing something? A look at the telnetlib code shows that its calling re.search(), not re.match(), so that wouldn't seem to be the issue.

Can anyone please offer suggestions on what I'm doing wrong?

Edit Added parens to the prompt example to better illustrate why expect() was not working as expected.

Was it helpful?

Solution 3

In previous attempts, I had pursued the regex option by placing .* at both ends of my search string, as well as doing a re.compile() to the search string before passing it/them to .expect(); all with no luck.

Thanks to jathanism's suggestion, I re-examined using regex, this time with the thought that expect() was, er... expecting 'regex' where I was thinking 'string'.

Sure enough, there were characters in my prompt string that expect was treating as regex symbols -- ()'s to be exact. Escaping the parens let expect() do its job.

OTHER TIPS

Don't forget if you are using the regex in python you can always use the raw (r'my string') method rather than adding in all the escapes; makes it more readable.

I got something to work. Lookig for # or % or $ prompts. As for your prompts, make sure that special characters are escaped. ( ). Maybe escape everthing just to be sure.

idx, obj, response = tn_conn.expect("\#","\%","\$",3)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top