Exploit-DB updates

Friday, November 4, 2011

Thursday, November 3, 2011

Python Curses Example / Tutorial

I wanted to make a small example tutorial on getting started with a curses UI in python. We'll get started by creating our screen and adding a simple string;


import curses

screen = curses.initscr() # Creates our screen
curses.noecho() # Keeps the keys we press from
curses.cbreak() # Takes input right away
screen.keypad(1)
screen.addstr(10,0,"Resist Monsanto!") # Add a string at 10,0
screen.refresh() # Refresh screen now that strings added
# While loop to wait for key events, then
while 1:
 key = screen.getch() # Get presse keys
 if key == ord("q"): break
curses.endwin() # Closes curses environment

This should result in a screen with the string "Resist Monsanto" in it. If we wanted to use colors we can create color pairs to use like so:

First we initiate the color scheme and than we will create a color pair;

curses.start_color()
curses.init_pair(1, curses.COLOR_CYAN, curses.COLOR_BLACK) # Creates a color pair as 1 with foreground cyan and background black

We can now use this color pair when adding a string for example;

screen.addstr(10,25,"Resist Monsanto!",curses.color_pair(1)) # Add a COLORED string located at (10,25)


This would result in the following script - http://pastebin.com/0EU7UKqZ

But lets say we wanted to get user input rather than just the key event and create a variable out of it, in this case we would use curses.getstr() function. Here we'll create a simple function to get our input called command().

def command():
 curses.echo() # Allows out input to be echo'd to the screen
 cmd = screen.getstr(0,1,15) # Creates an "input box" at the location (0,1) with an input buffer of 15

Now that we have out input as the string cmd, lets just verify it worked and echo it back out.

def command():  # Press "c" to start user input
 curses.echo() # Allows out input to be echo'd to the screen
 cmd = screen.getstr(0,1,15) # Creates an "input box" at the location (0,1) with an input buffer of 15 chars
 curses.noecho() # Turns echo back off
 screen.addstr(2,0,cmd,curses.color_pair(2)) # Adds users input


This would result in the following - http://pastebin.com/zVzrGz0n

You can use that input for whatever you'd like now, whether you want to issue a subprocess and pipe the ouput to the UI, or connect to a server, but that sums up this quick example. I'll delve more into it in a latter post. Take care!