Skip to content

Python shlex Examples

The Python shlex class makes it easy to parse strings into something more usable. How many times have to you rip through a string in order to make it into something more manageable.

Set up

Personally I like to use ArchLinux with the BlackArch repositories. You also can find my Black ArchLinux installation Guide on my blog. However any modern Version of Linux running Python3 will do. I will just be using the python console that comes up after typing the “python3” command on Linux.

You can also find all the example code over in my github page

shlex

Before we get into the examples of Python shlex make sure you have imported shlex.

import shlex
Import shlex

shlex.split

Probably the one you will use the most. shlex.split(string) takes a standard string and splits it into a list. Take for example the command “uname -r”, shlex.split will create a list with each component as an item in that list.

s = 'uname -r'
shlex.split(s)

This returns a list, like [ ‘uname’, ‘-r’ ]

shlex.split returns a list

A great example of this is if you want to provide a system command to the subprocess module and you don’t want to have to create the list your self. I have another article on subprocess module for python if you need to know more about it.

import shlex
import subprocess

command =  'grep 127.0.0.1 /etc/hosts'
commandList = shlex.split(command)
subprocess.run(commandList)
Feeding a string to subprocess via shlex

shlex.quote

If its need to wrap the string into a single quote then it can be done with the qoute method. Why would you want to do this. Well it can prevent unexpected results. Look up “command injection” if you want to read more.

filename = shlex.quote('/tmp;whoami')
 command = f"ls -l {filename}"
 print(command)
“whoami” trying to be injected

The output is not executable.

no command injection here.

shlex.join

shel.join is the oppisate of shlex.split. It takes an list and makes a string out of it.

a = [ 'ls', '-l', '/var/tmp' ] 
shlex.join(a)
shlex quote

Wrap-Up

Python shlex is very useful when using scripts to run Operating System commands or just to convert strings into lists and vice versa. Mostly only useful for Linux/Unix systems. If you have any comments or feed back please leave something in the comment section below.

Published inCTFProgrammingPython

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *