Author Topic: How to create an in-program command shell [Python]  (Read 938 times)

0 Members and 1 Guest are viewing this topic.

Offline sh4d0w_w4tch

  • Peasant
  • *
  • Posts: 73
  • Cookies: -1
  • Please do not feed the skids.
    • View Profile
    • 6c.nz
How to create an in-program command shell [Python]
« on: August 21, 2015, 03:11:11 am »
You can create a dictionary in Python and use it to make a command shell style interface within your program.  It's easier to work with and is more user friendly then a list of options with corresponding numbers.  You can even add arguments or allow stacking a list of commands.

This works by creating a dictionary and a list of functions that contain the code that you want to execute when a command is run.

Next we create a dictionary with a string that is the command and corresponds to the function it should run.

Finally, we create a command prompt and then execute the function from the dictionary based on the command.

Code: [Select]
def welcome():
    print 'Welcome to the demo program!'

def quit():
    print 'Terminating...'
    exit()

def begin():
    print 'Please select an option below: (Demo only)'

commands = {
    "welcome": welcome,
    "quit": quit,
    "begin": begin
}

while 1:
    cmd = raw_input(" prompt> ")
    commands[cmd]()

There's a few other things you can add that I didn't throw in for simplicity and because not everybody will want them.  You can remove whitespace from the command or convert the command to lower case as a way of making commands case insensitive.  You could add argument parsing by splitting the command string into a list and passing each argument into the function being run.

Code: [Select]
arguments = cmd.split(' ')
commands[cmd.lower()]()
DeepCopy | Can you name a VPN provider that's like "hey use our services to hack government sites and spam the internet. Please Abuse our services"

+Polyphony | paging master hackers of evilzone: i am here to learn about your black hatted tools to hack different viruses like facebook, sql, php, and other ring zero exploits


Offline kenjoe41

  • Symphorophiliac Programmer
  • Administrator
  • Baron
  • *
  • Posts: 990
  • Cookies: 224
    • View Profile
Re: How to create an in-program command shell [Python]
« Reply #1 on: August 24, 2015, 11:47:03 pm »
Nice job. But any decent programmer should have already done this in a few programs by now because we run in alot of if-else clauses and switch-case statements that sometimes this is the only and best option out there. You should see Deque or other programmers tell it to a person in quite alot of threads. And, oh, it isn't python specific only because i have seen it in alot of other language comments before, even think i have it in a Go program around here.
If you can't explain it to a 6 year old, you don't understand it yourself.
http://upload.alpha.evilzone.org/index.php?page=img&img=GwkGGneGR7Pl222zVGmNTjerkhkYNGtBuiYXkpyNv4ScOAWQu0-Y8[<NgGw/hsq]>EvbQrOrousk[/img]

Offline gray-fox

  • Knight
  • **
  • Posts: 208
  • Cookies: 52
    • View Profile
Re: How to create an in-program command shell [Python]
« Reply #2 on: September 24, 2015, 11:29:30 am »
Minor bump, but as op was originally talking about python I thought I throw maybe bit more pythonic example in about how to make in program shell. Most of you who have done some python coding are most likely familiar with cmd module which is part of standard library. Cmd module allows you quickly write own shell like application. It has automatic "help" command which usage is explained in my code example. It also has default tab autocompletion for made commands and previous commands can be displayed with up arrow.

Here is short example I quickly made to demostrate cmd modules usage. It mimics few familiar *nix commands in simple way.

Code: (python) [Select]
#!/usr/bin/python
import cmd, os, sys

class terminal(cmd.Cmd):

    def __init__(self):
        cmd.Cmd.__init__(self)
        self.prompt = "prompt> " #Default prompt is (Cmd)
     
    #Word after "do_" is actual command 
    def do_echo(self,input_string, *args):
        #*args is for some cmd module's default parameters
        print input_string   
               
    def do_ls(self, *args):
        """List files in directory"""
        #above comment makes actually help text which can be accessed via "help ls"
        self.files = filter(os.path.isfile, os.listdir('.'))
        self.dirs = filter(os.path.isdir, os.listdir('.'))
        for f,d in zip(self.files, self.dirs):
           print f,
           print d,
        print "/n"
         
    def do_cat(self, file_,*args):
       with open(file_, 'r') as self.f:
          for self.line in self.f:
             print self.line
   
    def do_exit(self,*args):
       sys.exit(0)
   
    def do_EOF(self,*args):
        #Exiting with ctrl+d. Throws error otherwise instead of exiting
        sys.exit(0)
   
    def cmdloop(self):
        try:
            cmd.Cmd.cmdloop(self)
        except KeyboardInterrupt:
            print "\n"
            self.cmdloop()
        except TypeError:
            print "*** Invalid syntax"
            self.cmdloop()
        except IndexError:
            print "*** Check arguments"
            self.cmdloop()
           
if __name__=="__main__":
    terminal().cmdloop()
   
Input after <command> is taken as one string, so for multiple arguments you can do same as suggested in op and use split().  But  actual command string is automatically not part of the aguments.