473,594 Members | 2,623 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Usage example for ANSI.py from the pexpect package

Hello folks:

(This message is also posted on the help forum at the pexpect
sourceforge page, but all indentation in the code got stripped away
when I submitted the post.)

For some time I've wanted to make use of the ANSI.py module in the
pexpect package to handle screen-based telnet sessions in Python, but I
could never break the ice with the thing. After reading an article by
Greg Jorgenson where he recounts using the package to help him solve a
problem for a customer, I wrote him asking if he could give me any tips
to help me get started. Greg very graciously sent me some code to use
as an example, and I've finally been able to make some headway, thanks
to him. I'm at least sputtering along now, so I wanted to take the
time to pass along a little code in case anyone else out there would
like to tinker with this tool but has a little trouble getting off the

The code I'm posting below is a script that establishes a telnet
connection with my Linux machine, starts the vim text editor, reads
some text from the splash screen over a range of coordinates, and moves
the cursor around. On my machine, the raw data sent over the telnet
stream after issuing the "vim" command is this:

(...and then a series of "~" symbols with line breaks-- takes up a lot
of screen space... :-))
~.[0m.(B.[24;63H0,0-1.[9CAll.[6;32HVIM - Vi IMproved.[8;34Hversion
6.3.54.[9;29Hby Bram Moolenaar et al..[10;24HModified by
..[1m<bu******@red hat.com>.[0m.(B.[11;19HVim is open source and freely
distributable.[13;26HHelp poor children in Uganda!.[14;18Htype :help
iccf.[1m<Enter>.[0m.(B.[7Cfor information.[16;18Htype
:q.[1m<Enter>.[0m.(B.[15Cto exit.[17;18Htype :help.[1m<Enter>.[0m.(B
or .[1m<F1>.[0m.(B for on-line help.[18;18Htype :help
version6.[1m<Enter>.[0m.(B for version info.[1;1H

The script is used to process the raw stream and read characters 25
through 37 on row 18, and it correctly reports "help version6" as the

A great deal of the code that follows is either blatantly
cut-and-pasted from the sample Greg sent me, or has been modified only
slightly. I have included some code of my own which makes use of the
set_option_nego tiation_callbac k method of the Telnet class, which can
be used to establish an agreement between the client and server on how
the session will proceed. Learning how to use that method was a hurdle
for me when I did it, maybe someone down the line will find an example
useful. Beware, though-like I said, it's my own code, and I'm a
rookie. There's probably a lot of room for improvement in what I came
up with.

One thing that I think is worth noting-none of the code below depends
on the pexpect module itself. It just uses the standard telnetlib to
establish the connection, and then uses the ANSI, screen, and FSM
modules from the pexpect package to interpret the output of a
screen-based application. The upshot of this is that the pty module is
not required, so you can use this with the native Windows version of
Python. Cygwin is not required.

Finally, I'd like to express my thanks to Mr. Jorgensen one more time.
Greg, you really helped out when I was ready to become frustrated. It's
people like you that make the 'net a nicer place to work and play!

OK, without further ado, here's the script-

#! /usr/bin/env python
""" ansi_py_usage: example for usage of the ANSI.py module """

from telnetlib import Telnet
from telnetlib import DO, DONT, WILL, WONT, theNULL, TTYPE, IAC, SB, \
import ANSI

global host_address,us ername,password

host_address='a ddress_of_the_m achine_you_want _to_connect_to'
username='your_ username' # P.S.-- it's very bad practice to hard-code
password='your_ password' # in a hostname, username, and password!
terminal_type=' vt100'
class AnsiPyTestImple mentation:
def __init__(self):
self.conn = None
self.crt = ANSI.ANSI(25,80 )

def login(self, host, username, password):
# empty the read buffer and check the connection
self.conn.read_ eager()
self.conn = None
tries = 45
while tries > 0:
print "logging in..."
if self.conn is None:
# The following is an example of how to use the
# set_option_nego tiation_callbac k method of the
# Telnet function. When any sub-negotiation
# requests are received from the server during the
# client/server hand-shaking, a user-defined
# function can be called to handle the situation.
self.conn = Telnet()
self.conn.set_o ption_negotiati on_callback(sel f.neg)
self.conn.open( host)
self.waitfor("l ogin: ", 5)
self.sendln(use rname)
self.waitfor("P assword: ", 2)
self.sendln(pas sword)
self.sendln("") ;
self.waitfor("$ ", 2)
tries = tries - 1
self.conn = None
print "timed out"
raise IOError, "timed out (login)"

def logout(self):
if self.conn:
self.sendln("ex it")
self.conn.close ()
self.conn = None
print"logged out"
print"not logged in"

def neg(self, sock, command, option):
# Here's a function I came up with to handle sub-negotiation.
# During session negotiation, the server can ask a series of
# "will you or won't you" questions of the client. One of
# those questions happens to be:
# "Will you tell me what terminal type you are?"
# This question is the only one out of the possible list of
# such questions that I respond with "Yes, I will." Then later
# the function reports that the terminal type is a DEC VT-100.
# If you don't do the sub-negotiation and the server demands
# to know the terminal type, the Telnet function will report
# that the terminal type is simply "network". No server will
# recognize this, and some will refuse to even start a session
# with you using some default terminal type.
# A couple of good links--
# http://www.cs.cf.ac.uk/Dave/Internet/node136.html
# http://www.scit.wlv.ac.uk/rfc/rfc8xx/RFC854.html
negotiation_lis t=[
['TM',WONT,'WONT '],
['BM',WONT,'WONT '],
if ord(option)<40:
received_option =negotiation_li st[ord(option)][0]
response=negoti ation_list[ord(option)][1]
print_response= negotiation_lis t[ord(option)][2]
received_option ='unrecognised'
print_response= 'WONT'
if command==DO:
print "Received request to DO %s, sending %s" % \
(received_optio n,print_respons e)
sock.sendall("% s%s%s" % (IAC, response, option))
elif command==DONT:
print 'Received the DONT command'
elif command==WILL:
print 'Received the WILL command'
elif command==WONT:
print 'Received the WONT command'
elif command==theNUL L:
print 'Received the NULL command'
elif command==SB:
print 'Received the SB command'
print ord(option)
print self.conn.read_ sb_data()
elif command==SE:
print 'Received the SE command'
print repr(self.conn. read_sb_data())
sock.sendall("% s%s%s%sDEC-VT100%s%s" % \
(IAC,SB,TTYPE,c hr(0),IAC,SE))
print 'Sent all'
print 'Received something, don''t know what.'
print ord(option)

def getcrt(self, row, colstart, colend):
return self.crt.get_re gion(row, colstart, row, colend)[0]

def send(self, s):
self.conn.write (s)

def sendln(self, s):
self.send("%s\r " % s)

def updatescreen(se lf, buf):
self.crt.proces s_list(buf)

def waitfor(self, match, timeout=None):
s = self.conn.read_ until(match, timeout)
if timeout is not None:
n = len(match)
if s[-n:] != match:
raise IOError, "timed out (waitfor)"
self.updatescre en(s)
return s

def DoIt(self):
# This is the method called by main(), which in turn uses
# methods from ANSI.py and screen.py to process the raw data
# from a screen-based application (vim in this case)
self.login(host _address,userna me,password)
print "Couldn't log in!"
self.sendln("vi m")
print "vim started"

# [1;1H is the last bit of the vim splash screen that my
# server sends me. The self.waitfor method is used to look
# for this sequence of characters. Once it arrives, we
# know the buffer is ready to be processed.
raw_telnet_data =self.waitfor("[1;1H",3)

print "\nThe raw telnet data sent over the network was:\n"
print raw_telnet_data + "\n"

# The vim splash screen lists the help version on row 18,
# characters 25 through 37. We can locate that text in the
# processed buffer.
help_version = self.getcrt(18, 25,37).strip()
print "Text found on row 18, columns 25 through 37, was: ",
print help_version + "\n"

# The following shows you a screen-shot of the processed
# buffer.
print "ANSI-fication of the raw telnet data received",
print "looks like this:\n"
print str(self.crt)

print "vim failed to start"
raise IOError, "service unavailable (start)"
# ANSI.py can keep up with where the cursor is...
if self.crt:
print "Right now the cursor is at row " + \
repr(self.crt.c ur_r)+ ", column " + \
repr(self.crt.c ur_c)+"\n"
print "So now we'll send some keystrokes to change",
print "that, and then report back the new position..."
print "Now the cursor is at row " + \
repr(self.crt.c ur_r)+ ", column " + \
repr(self.crt.c ur_c)+"\n"
print "cursor is at 0,0"
print "Couldn't get cursor position!"


if __name__=='__ma in__':
w = AnsiPyTestImple mentation()

Jul 18 '05 #1
0 3094

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

by: Maurice LING | last post by:
I know this might sounds wierd but I'm wondering if I can use pexpect or os.popen3 function to invoke and control python interpreter to make it act like a python interpreter in python? maurice
by: ThyRock | last post by:
I am working on a WebRequest accessing the US Postal Service WebTools test API. This service uses a DLL file (ShippingAPITest.dll) with a query string which includes XML. The web service accepts the query string with no url encoding. I must pass the <> characters as they are in the query string. If these characters are url encoded the service rejects the request. This API Url is http://testing.shippingapis.com/ShippingAPITest.dll
by: funkyj | last post by:
I love pexpect because it means I may never have to use expect again (I don't do any heavy expect lifting -- I just need simple tty control)! As a python advocate I find it embarassing how difficult it is do the following in python (without pexpect): - logon to a remote system using ssh - do an 'ls' and exit the remote shell - print the output from the remote shell session.
by: dwelch91 | last post by:
I'm having a problem using pexpect with 'sudo' on Ubuntu 6.06 (Dapper). Here's the program: #!/usr/bin/env python import pexpect import sys child = pexpect.spawn("sudo apt-get update") child.logfile = sys.stdout
by: half.italian | last post by:
Hi all. I try not to post until I am stuck in hole with no way out. I fought with this for several hours, and am currently in the hole. I'm doing a proof of concept for creating afp shares dynamically through a web interface from a client machine. I use a bit of php to setup a simple form, and then have the php execute my python script on the server. The python script tries to 'su' to root to create the share, create dirs, set perms,...
by: Kevin Erickson | last post by:
Hello, I am attempting to use pexpect in python to copy files from a server using scp; the copy works however exceptions are thrown and it exits unsuccessfully. Below is the a sample code and the error: #Begin Code import sys import pexpect
by: asgarde | last post by:
hello, I'm new in Python and i would like to use Pexpect to execute a root command (i want to mount via a Pyhton script a drive) so that's my script for the moment : from os import * import pexpect import os
by: crybaby | last post by:
I need to ssh into a remote machine and check if mytest.log file is there. I have setup ssh keys to handle login authentications. How do I determine if mytest.log is there by using Pexpect. What I have done so far is spawned a child for ssh. 1) Now what do I do to execute shell_cmd(ls and grep), spawn another child? 2) Can I use the same child that was spawned for ssh, if so how?
by: yellowblueyellow | last post by:
Hey , I need to SSH into a server .. ( using pexpect the username is 'admin' and password is 'abc123' so far i have the following code import pexpect import sys import time import os
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.