Skip to main content
Python 3

Python – Primer

By April 17, 2013September 12th, 2022No Comments

We introduce Python in our Linux Essentials mini series, but to kick of this series I have reused the python primer from our Linux essentials trainer to start us of here

Although not explicitly part of the LPI Linux Essentials objectives, we did introduce Python along with Perl and Bash scripting within topic 1. It can be guaranteed though that Python will help with your system administration of Linux. The LPI objectives do call for a little BASH scripting but I am sure we will include a Perl primer for you as well. So please do not get too frightened by this, it is still early days; but I want to include some tasters of what is to come in the world of Linux

Of course, we have to make sure python is installed and I am using and I have installed pythom 3 onto my openSUSE 12.3 system. I will create my python scripts within my home and bin directory (/home/andrew/bin) so they are included within may PATH variable.

We start by using the ever present hello world.

#!/usr/bin/python3
print("Hello World")

Now we move away from hard coding the message to allow for use to pass the message as an argument to the script

#!/usr/bin/python3
import sys
print(sys.argv[1])

Now we test for root access, ultimately we want to write to the hosts file:

#!/usr/bin/python3
import sys, os
if not os.geteuid()==0:
    sys.exit("nOnly root can do thatn")cat
print(sys.argv[1])

And finally we change the print message to write to the file:

#!/usr/bin/python3
import sys, os
if not os.geteuid()==0:
    sys.exit("nOnly root can do thatn")
hosts=open("/etc/hosts","a")
hosts.write("nWritten " + sys.argv[1] + " to /etc/hosts")
hosts.close()

As I say don’t be put off by this , take this just as a taster and the video will help 🙂 Please do understand that there is a lot more error handling that we should build into the script but trying to keep it as bare bones as possible will make the script easier to follow.