Shell escape a string to safely use it as a token in a shell command (backport of Python shlex.quote for Python versions 2.x & < 3.3)
Project description
Source Repository: https://github.com/chrissimpkins/shellescape
Description
The shellescape Python module defines the shellescape.quote() function that returns a shell-escaped version of a Python string. This is a backport of the shlex.quote() function from Python 3.4.3 that makes it accessible to users of Python 3 versions < 3.3 and all Python 2.x versions.
quote(s)
From the Python documentation:
Return a shell-escaped version of the string s. The returned value is a string that can safely be used as one token in a shell command line, for cases where you cannot use a list.
This idiom would be unsafe:
>>> filename = 'somefile; rm -rf ~'
>>> command = 'ls -l {}'.format(filename)
>>> print(command) # executed by a shell: boom!
ls -l somefile; rm -rf ~
quote() lets you plug the security hole:
>>> command = 'ls -l {}'.format(quote(filename))
>>> print(command)
ls -l 'somefile; rm -rf ~'
>>> remote_command = 'ssh home {}'.format(quote(command))
>>> print(remote_command)
ssh home 'ls -l '"'"'somefile; rm -rf ~'"'"''
The quoting is compatible with UNIX shells and with shlex.split():
>>> remote_command = split(remote_command)
>>> remote_command
['ssh', 'home', "ls -l 'somefile; rm -rf ~'"]
>>> command = split(remote_command[-1])
>>> command
['ls', '-l', 'somefile; rm -rf ~']
Usage
Include shellescape in your project setup.py file install_requires dependency definition list:
setup(
...
install_requires=['shellescape'],
...
)
Then import the quote function into your module(s) and use it as needed:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
from shellescape import quote
filename = "somefile; rm -rf ~"
escaped_shell_command = 'ls -l {}'.format(quote(filename))
Issue Reporting
Issue reporting is available on the GitHub repository
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Hashes for shellescape-3.4.1-py2.py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 3ff2aeb6ce2c5a4e6059fe4a2a745a824f5a3834fe8365a39c5ea691073cfdb6 |
|
MD5 | 5bc6f494f210878685dc9492fbce52e2 |
|
BLAKE2b-256 | 51b6986c99a10040beaaefca1ad6c93bd7738cb8e4f52f6caed13d3ed1caa7e4 |