Weblogs

Fun With Python OS Imports

Introduction

In this article we are going to explore about the ways in which we can import and use os module in python. This can be applied to other modules based on the context.

The Standard Way

1import os
2
3os.system('ls')
1from os import system
2
3system('ls')

Using importlib

1import importlib
2
3importlib.import_module('os').system('ls')

Using __import__

1os = __import__('os')
2
3os.system('ls')

Using sys

1# If `sys` and `os` is already imported or accessible.
2
3sys.modules['os'].system('ls')

Using eval

1os = eval('__import__("os")')
2
3os.system('ls')

Using exec

1exec('import os; os.system("ls")')

Other Ways

Using Hex

1eval(bytes.fromhex('5f5f696d706f72745f5f28226f732229')).system('ls')
2
3exec(bytes.fromhex('696d706f7274206f733b6f732e73797374656d28226c732229'))
4
5__import__(bytes.fromhex('6f73').decode()).system('ls')

Using String Manipulation

1__import__(''.join(['o', 's'])).system('ls')
2
3__import__('o1s1'.replace('1', '')).system('ls')

Using other packages

1# If already imported package exposes `os`
2
3logging.os.system('ls')
4
5getattr(logging, 'o1s1'.replace('1', '')).system('ls')
6getattr(logging, bytes.fromhex('6f73').decode()).system('ls')
1getattr(getattr(logging, 'o1s1'.replace('1', '')), 's1y1s1t1e1m1'.replace('1', ''))('ls')
1import operator
2
3f = operator.methodcaller('o1s1'.replace('1', ''))
4os = f(logging)
5
6f = operator.methodcaller('s1y1s1t1e1m1'.replace('1', ''), 'ls')
7f(os)
1import operator
2
3l = globals().get('l1o1g1g1i1n1g1'.replace('1', ''))
4
5o = getattr(l, 'o1s1'.replace('1', ''))
6
7f = operator.methodcaller('s1y1s1t1e1m1'.replace('1', ''), 'ls')
8f(o)

Conclusion

We can also combine hex, replace and other methods in different ways. There are a plenty of ways to use the os package even if we restrict it somehow. I’m still exploring the possibilities. If I come to know more possibilities, I’ll update here.

#python #os #security