Linux Tutorials
Linux Tutorials
com
Hacking University: Learn Python Computer
Programming from Scratch & Precisely Learn
How The Linux Operating Command Line
Works 2 Manuscript Bundle
By Isaac D. Cody
www.Ebook777.com
www.Ebook777.com
QUICK TABLE OF CONTENTS
This book will contain 2 manuscripts from the Hacking Freedom and Data
Driven series. It will essentially be two books into one.
Hacking University Senior Edition covers a everything you need to know about
Linux
Both books are for intended for beginner’s and even those with moderate
experience with Python and Linux.
www.Ebook777.com
Hacking University: Junior Edition. Learn Python
Computer Programming from Scratch
Introduction
Related Software
Online Resources
History of Python
Benefits of Python
Hello World
Programming Concepts
Variables
Variable Types
Input
String Formatting
Example Program 1
Decision Structures
Conditional Operators
Example Program 2
Loops
Example Program 3
Example Program 4
Functions
Example Program 5
Classes
Special Methods
Example Program 6
Inheritance
Example Program 7
Modules
Example Program 8
Common Errors
Conclusion
Related Titles
Copyright 2016 by Isaac D. Cody - All rights reserved.
This document is geared towards providing exact and reliable information in regards to the
topic and issue covered. The publication is sold with the idea that the publisher is not
required to render accounting, officially permitted, or otherwise, qualified services. If
advice is necessary, legal or professional, a practiced individual in the profession should be
ordered.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either
electronic means or in printed format. Recording of this publication is strictly prohibited
and any storage of this document is not allowed unless with written permission from the
publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability,
in terms of inattention or otherwise, by any usage or abuse of any policies, processes, or
directions contained within is the solitary and utter responsibility of the recipient reader.
Under no circumstances will any legal responsibility or blame be held against the publisher
for any reparation, damages, or monetary loss due to the information herein, either directly
or indirectly.
The information herein is offered for informational purposes solely, and is universal as so.
The presentation of the information is without contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark
is without permission or backing by the trademark owner. All trademarks and brands within
this book are for clarifying purposes only and are the owned by the owners themselves, not
affiliated with this document.
Disclaimer
Related Software
For enhancing your Python skill, use an IDE. If you have not
downloaded it yet, Atom is highly recommended for Python programming.
Atom is customizable, in that you can install add-ons at any time to make
programming easier. “autocomplete-python” is one such add-on that can guess
what you are typing and automatically fill in the rest of the command.
VI and Emacs are two other popular text editors for programmers. Both
are considered highly advanced and optimized for writing code, but a bit of a
“flame war” exists between fans of both softwares. For the Linux Python
programmer, investigate the two text editors and test whether it helps with
Python workflow.
After you have finished a particularly useful Python program and wish to
distribute it to users, you have to keep in mind that many of them do not have
Python installed and will likely not want to install it just to run your program.
PyInstaller (http://www.pyinstaller.org/) is a piece of software that builds your
Python script and the needed modules into an .exe file that does not need
Python to run. It is a handy software should distribute your applications.
Online Resources
For obtaining online help related to Python, you can always check the
online documentation (https://www.python.org/doc/). The documentation
contains examples and manual pages for every function built-in to Python and
its included modules.
For times when programming code just does not work, you can always
turn to search engines to resolve your problem. Typing in the error text into
Google can turn up other programmers who also had the same problem and
posted online. If the problem cannot be fixed by observing other code,
websites such as Stack Overflow (http://stackoverflow.com/) are notoriously
helpful in resolving code issues. Make an account their and post your
problem politely and somebody will probably help you out.
Finally, there are websites that offer tutorials online about how to learn
intermediate and advanced Python programming. http://www.learnpython.org/
is one particularly exemplary one, but the sheer amount comes from the fact
that Python is highly used and well understood. For any time Python help is
needed, a quick internet search may solve your curiosities.
The Job Market
Overall, finding a Python job is easy because of the current market, but
also difficult because you need to know Python intimately. Dedicate yourself
to applying for as many positions as possible and eventually a job will appear.
History of Python
The term “scripting language” refers to the fact that written code is not
actually compiled, but rather it is interpreted by an application. Normally this
means that scripting languages are not nearly as powerful as actual
programming languages. For Python, though, the opposite is true- the language
remains one of the most powerful available for web servers and desktop
clients. Development of Python continued throughout the 1990’s until version
2 was released in 2000. The interpreter behind Python became intricate
enough that current versions of Python are almost indistinguishable from lower
level programming languages.
When first starting out learning how to program, the huge amount of
options, information, and advice can be truly intimidating. Some experts claim
that the difficult but time-honored C language is the best start, but other
professionals say starting on an easier language such as Java or Python will
give the learner a chance to actually absorb key concepts. Python is
recommended for this exact reason- programming will not be as foreign and
confusing by starting with a straightforward scripting language.
Large companies such as Google, Disney, NASA, and Yahoo all use
Python for their own programs; having Python knowledge could potentially
land a programmer a job working at a high-profile organization. Moreover,
because Python is continuously developed today with new features always
being added, interest in the language will continuously increase with time.
More companies will discover that Python is an exceedingly useful
programming language, so learning it now will prepare you for the future.
Benefits of Python
In addition to being easy and fast, Python also has various other
benefits. Python is very portable, meaning that Python code can run on a
variety of different operating systems. Windows, Mac OSX and Linux
distributions are all supported directly, and code written on one platform can
be used on all of them.
Ease of development and testing also propel Python above other similar
languages. Code can be run instantly with the interpreter which allows for
rapid prototyping. Being able to quickly test out code means that bugs can be
fixed quickly, allowing more time for other development goals.
Conclusively, Python is the perfect language for beginners. Both simple
to develop for and learn, Python is also decently powerful. Fantastic for
newcomers and those just starting out programming, Python remains the top
choice of technology companies everywhere. Learning the language will
prove to be useful now and into the future as its popularity continues to grow.
Setting up a Development Environment
Now that there is a development environment set up, you can continue
onwards to begin writing your first Python program.
Hello World
Next, we save the file. In IDLE (and most IDEs such as Atom) one must
go through “file” and click “save as”. In Nano ctrl+x must be pressed. Name
the file with a “.py” extension and save it in an easily accessible directory-
your desktop is perfectly fine. For this demonstration we will name the file
”test.py”.
If the above programming code was copied exactly, the output “Hello,
World!” will be seen. The program will run and then exit back to
terminal/prompt. Not entirely glamourous, but a worthy first step into learning
Python.
Programming Concepts
Anything can be put within the quotations of the print function and it will
be written to the console. Since Python starts at the beginning of a script and
reads lines individually, multiple print functions can be placed one after
another like so:
print (“Notice how each print command puts the text on a new line!”)
After saving and running the file, all three functions will print their
respective parameters. As mentioned previously, the quotations explain that
text will be displayed. By forgoing quotations, numbers can be displayed
instead.
print (42)
Python starts at the beginning of the script file and works its way down
one line at a time until no more lines are found, in which case the program
exits back to prompt or terminal.
Variables
lucky_number = 7
And then we can use the print function to view the variable we created.
print (lucky_number)
Because Python starts at the top of a program and works downwards, the
above lines need to be in the correct order. If lucky_number is not first
created, then print() will return an error for attempting to call a variable that
does not yet exist.
Variables can contain values of multiple types. Our first variable was
assigned a numerical value, but Python has methods for handling values of
different types as well.
secret_message = “rosebud”
print (secret_message)
first_num = 2
result = 3 + first_num
print (result)
first_num = 3
result = 3 + first_num
print (result)
Both integers and floats can easily perform calculations using the above
operators. Note, though, that integers will generally return integer answers
(whole numbers) while floats will always return an answer with a decimal
point. Python can usually transform an integer into a float when it is needed,
but good programming form comes from choosing the correct data type at the
appropriate time. For example, see how floats are used in the program below:
first_number = 5.0
second_number = 3.0
result = first_number / second_number
print (result)
first_number = 5.0
second_number = 3.0
name = “Bill”
print (name)
my_string = “Hello,”
my_string2 = “World! ”
print (my_string2 * 3)
The output would be “Hello, World!” for the first print(), and “World!
World! World!” for the second print(). The addition operator combines two
strings together into one massive string, and the multiplication operator repeats
a string the specified number of times.
Input
When a program reaches this line, it will display the text specified and
wait for user input. Whatever is input will be assigned to favorite_number,
which can be called just as any other variable.
There are a lot of new nuances going on in this program. For example,
int() is used to convert the input into an integer. Notice how int() surrounds the
entire input() function, which happens because input() must be passed as the
entire parameter of int(). Next, the print statement is printing multiple bits of
output, and the equation “favorite_number + 2” is evaluated before being
printed.
Using int() will always return an integer answer, but float() could have
been used to extract a decimal answer instead. The int() function works
essentially by transforming the string “3” into the number 3. Definitely
remember to include it whenever getting numerical input.
String Formatting
Being able to display strings with print() is useful, but sometimes our
programs require us to display variables within them. To actually insert a
variable into a string without first editing it or combining multiple variables,
we can use a “string formatter”. The format() function can be included within
a print() statement to do positional formatting of variables.
dog_name = “Rex”
When you run the above code, it automatically replaced the brackets {}
with the supplied variable. The format() is placed directly after the string it
will be editing, and before the closing parenthesis. So when the code is run,
the console outputs “My dog’s name is Rex…”. Without using format(), we
would have had to use a multi-line complicated print setup. But format()’s
greatest use comes from situations with multiple variables.
dog_name = “Rex”
dog_age = 12
print ("{0} is {1} years old. They have a {3} GPA, probably because they
have {2} pets.".format(user_name, user_age, user_pets, user_GPA))
Depending upon the medium in which you are reading this publication,
some of the above lines may have word-wrapped to multiple lines. This is not
how you should be typing it into a text editor though, as the print() line is one
single command. Furthermore, copy and pasting from this document may
introduce extra characters that Python does not understand. Therefore the
correct way to input project 1’s code is by typing it out yourself.
Homework program:
Now that the basics of Python 3 are explained, we can begin to offer
truly interactive programs by implementing decision structures into our code.
Decision structures are pieces of code (called conditional statements) that
evaluate an expression and branch the program down differing paths based on
the outcome. Observe the following example:
if (user_input == 2):
print ("Correct!")
else:
print ("Incorrect...")
First we obtain input from the user. We test user_input against 2 (the
correct answer). If the conditional statement turns out true, then the program
will print “Correct!”. However, if the user provides the wrong answer Python
will return “Incorrect...”. There is a lot of new concepts going on here, so we
will break it down line by line.
If the user had input the correct answer of 2 instead, the if statement
would evaluate to true and the console would print “Correct”. In that situation,
the else statement would not run at all. Focus once again on the indented code
and understand that those lines are indented because they are part of the “if”
and “else” code blocks. Also realize that only one statement from a decision
structure can ever run in a program, so if “else” runs, that means “if” did not
run. Likewise a program that has “if” activated will not run the code block
under “else”. Conditional statements are not limited to single lines of code, as
you can see below.
if (user_input == "Python"):
print ("Correct!")
else:
print ("Incorrect...")
Double equal signs (==) are only one of the many operators that can be
used to create a conditional expression. This small list shows other operators
in Python.
== - Equal to
For situations that require more than just two potential outcomes, the
keyword “elif” can be used.
else:
Elif is a keyword that can be used to split the decision making process
into multiple branching paths. Between if and else statements, any number of
elif conditionals can be used. Also, another new keyword is used above-
“and”. Our first comparison checks to see if age is less than or equal to 18
AND greater than 0. Therefore that conditional will only evaluate to true if the
age value satisfies both requirements. Pretend the user input 75. The first
statement evaluates, and 75 is indeed greater than 0, but it is not also less than
18, so that statement is skipped. Then, the first elif is evaluated. Age is not
greater than 80, so that statement is skipped as well. Thirdly, age is definitely
between 18 and 80, so the console prints “Ah, a good age to learn” and then
skips the else statement altogether.
Remembering that only one statement in a decision “tree” can ever run,
we can see that any elif that activates essentially runs its code block and then
breaks from the decision structure. Else is used as a “catch-all” type
expression in our above program. Any invalid input, such as “-1” would be
picked up by else and displayed as such. Good programming form comes from
catching potential user errors like this, and as an aspiring programmer you
should always be expecting the user to incorrectly input values whenever the
chance arises.
print("Python Quiz!")
answered = 0
correct = 0
print()
print("A: 1, B: 2, C: 3")
print()
correct += 1
print ("Correct")
else:
print ("Incorrect")
print()
print("How many 'else' statements can be in a decision tree?")
answered += 1
print()
correct += 1
print ("Correct")
else:
print ("Incorrect")
print()
answered += 1
print()
if (user_answer == "B" or user_answer == "b"):
correct += 1
print ("Correct")
else:
print ("Incorrect")
print()
if (correct == 3):
print ("Congratulations! Good score.")
else:
print ("Go back and read over the section again, I'm sure you'll get it.")
Homework program:
answer = 0
print ("Correct!")
answer = 0
if (answer != 2):
print ("Incorrect...")
print ("Correct!")
Another common loop is the “for” loop. For is different from while in
that a for loop runs through a range of numbers or a set of values instead of
checking a conditional.
print (user_variable)
For takes the specified variable “user_variable” and uses the supplied
range. The variable will be initialized at 1, and it will be iterated every time
the function loops. By observing the output we can see how this works.
1
2
3
4
print (user_variable)
For example, only “range” is left out here, but the output is very
different.
1
5
Python runs the loop with the first value, 1, and then runs it with the
second value, 5. We will learn that using for loops this way is especially
useful for lists, dictionaries, and tuples.
Lastly, loops can be broken with the break() function. Bad programming
form can lead to infinite loops, but including break() as a safeguard might save
a user’s computer from crashing.
Example Program 3 – project3.py
print("Adding simulator")
line = "a"
total = 0
line = input("")
if (line == ""):
break
total += int(line)
Homework program:
Lists are another data type beneficial to talk about. A list is an array of
values that are grouped together into a single variable. The single variable can
then be used to call upon any of the “sub variables” it contains. They are
mostly used for organization and grouping purposes, and also to keep related
variables in a similar place. List variables are created by initializing them.
state = "Texas"
Entry 0 1 2 3
number:
Data value: 8 “West state “A”
Elementary”
A list could be initially declared with 3 entries, and it would have the
range 0-2. The number of entries is nearly infinite, and it is only limited by the
computer’s memory and the amount of variables the programmer fills it with.
state = "Texas"
jack_info.append(22)
The new additions to the program change the list ever so slightly to now
have a new set of values.
Entry 0 1 2 3 4
number:
Data value: 9 “West state “A” 22
Elementary”
Before continuing onwards, it is worthy to note a few more features
about the string data type. Strings are actually lists that contain character
values. As an example, take the string “Hello, World!”. Broken down as a
list, it would look like this:
Entry 0 1 2 3 4 5 6 7 …
Character H e l l o , W …
And likewise, individual entries can be displayed from the string list.
Moving onwards, tuples are another data type within Python. They are
declared by using parentheses instead of square brackets. Tuples are actually
static lists, or lists that cannot be edited. They are used when the programmer
needs to ensure a range of data cannot change.
Here, the dictionary pet_dict contains three values: “Total”, “Dog”, and
“Cat”. The entries are declared by naming the entry within quotations and then
supplying a value. Those entries are called by specifying the name of the entry,
such as with pet_dict[“Dog”] to access the value stored within. An
unprecedented amount of organization is available when using dictionaries
because they resemble a database in form. Likewise, they can be changed,
updated, removed, or added to at any time within a program.
print (albums)
The humorous example above is a simple dictionary used to store the
number of albums a person has. At the beginning the dictionary has a set
number of albums for each band, but the second line has the collector gaining a
new Milkduds album. That line also uses a new code shortcut. Whenever
“+=” is used, the code is actually expanded to be “albums["Milkduds"] =
albums["Milkduds"] + 1”, but much time and space is saved in the program by
using the shorthand. Third line has the collector realizing they only had 2
7750’s albums, so the command changes the value of the entry altogether. Next
update() is introduced. It shows how an entirely new entry can be added to the
dictionary. Sadly, though, Harold Gene is deleted from the dictionary because
the collector sold away the album. Finally, printing the entire dictionary can
be done by not specifying any entry.
number_grades = 0
grade_list = []
total = 0
print()
number_grades += 1
grade_list.append(grade)
Homework program:
Devise code for more math functions, such as medians and modes.
Functions
Every function used thus far has been built-in to Python and programmed
by Python’s developers. Functions are actually code shortcuts, as functions are
condensed versions of code that take data as parameters, run longer blocks of
code behind the scenes, and then return a result. The use of functions is to save
time and code when doing commonly repeated tasks. Python retains the ability
for programmers to write their own functions, and they are done like so:
def happy(name):
happy("Dana")
intdiv(first, second)
First, the UDF is declared. This code does not run automatically
because it has not yet been called. The program actually starts on the fifth
line. The variable “first” is declared within the main program’s scope based
on the user’s input. So too is the variable “second”. The UDF “intdiv” is
invoked with first and second as the two parameters. The variables are passed
as parameters so they can be transferred into the UDF. First and second are not
actually leaving their scope, though, because the UDF uses the variables
num_one and num_two to perform calculations.
Variables can be passed back from a UDF by using the return keyword.
orig_num = base
return base
So when we call the function like above, the answer (base) is given
back as the result and assigned to the variable “answer”.
Conclusively, user defined functions can save a lot of time for programs
that must repeatedly call a block of code. UDFs can just contain other
functions, like our Happy Birthday UDF, or they can help simplify complicated
code, such as our exponential multiplication UDF. You must remember that
variables are defined within a scope that they cannot leave. However, values
can be passed from the main program to a UDF by supplying them as
parameters, and values can return from a UDF by using the return keyword and
assigning the result to a variable.
Example Program 5 – project5.py
def cm_to_inch(cm):
inch = cm * 0.39
return inch
def inch_to_cm(inch):
cm = inch * 2.54
return cm
print("Inch/cm converter")
print("1: Convert cm to inch")
if (choice == 1):
if (choice == 2):
Homework program:
Classes are a feature of Python that bring it more in line with some of
the more difficult programming languages. They are essentially “programs
within programs” because of how many features you can put into one.
Moreover, it is good programming form to use classes for organization.
Object-oriented languages such as Python occasionally show their object roots
through concepts like these, whereas objects contain attributes in the form
“object.attribute”. See the example below to understand.
class student:
self.name = name
self.grade = grade
self.gpa = 0.0
The class that we create is called “student”, and student contains its own
variables. Classes give us a way to organize objects and give them personal
attributes. So instead of having student1_name, student1_grade,
student2_grade, etc… as different variables, they can be consolidated by
belonging to a class. Within a program, the class declaration goes at the very
top. Just like a UDF, it does not actually run in the main program until called.
Our newly declared “student” class is used to create the student1 object
with the attributes “Tim” and “Freshman”. This would have previously taken
two lines, but it is condensed considerably with classes. Classes
compartmentalize the related variables of the object so that each “student”
declared has the 3 properties “name”, “grade”, and “gpa”. The second line of
our class declaration contains __init__, which is a “method” (user defined
function) that runs when an object in the student class is created. Init’s
parameters are the ones required when creating that object. Self is not actually
a parameter, it just refers to “student”, but “name” and “grade” are required,
which is why we included them when creating “student1”. Attributes of
student1 can be called like so:
print (student1.name)
Which would simply print “Tim”. We did not declare the GPA variable
during the student1 initialization, so we can do that with an assignment
statement.
student1.gpa = 4.0
student1.grade = “Sophomore”
Looking back to our custom class, we can expand upon it to achieve user
defined functions within the class itself.
class student:
self.name = name
self.grade = grade
self.gpa = 0.0
def record(self):
print (student3.record())
The __init__ stays the same, but we add a UDF definition with the name
“record”. It passes the parameter self (because it has to refer to the class) and
returns a formatted string. In our actual main program student3 is created.
Finally, we call the UDF with student3.record() (object.function). It returns
our formatted string, and therefore it is printed out by print().
Special Methods
Other special methods exist, and they are called on different events.
class student:
self.name = name
self.grade = grade
self.gpa = 0.0
def __str__(self):
return "{}".format(self.name)
def record(self):
print (student4)
total_foods = 0
self.name = name
self.calories = 0
self.foodgroup = ""
food.total_foods += 1
def __del__(self):
food.total_foods -= 1
def __str__(self):
return "{}".format(self.name)
def get_total():
return food.total_foods
def record(self):
food1.foodgroup = "Vegetables"
food2.calories = 100
food2.foodgroup = "Grains"
print (food.get_total())
del food2
print (food.get_total())
As the program creates a food, 1 is added to total_foods. Then, a food
object is deleted so 1 is taken away. The console prints 2, then 1 to show how
our UDF can be called to check the class variable. Keeping track of the
number of something is a common use for class variables, but they are highly
useful for other situations as well.
Example Program 6 – project6.py
class house:
self.name = name
self.bedrooms = bedrooms
self.bathrooms = bathrooms
self.cost = cost
x += 1 #wait a while
print("Sold!")
del house1
Homework program:
In your more robust and expansive programs, you might use multiple
related classes. As an example, think of the program where you must
categorize devices on a network. Each device type (desktop, laptop, phone,
etc…) will have its own class, but you will ultimately be repeating commonly
used attributes. Both desktops and laptops will have names, departments, and
IP addresses, but they will also have a few distinct variables specific to them
such as Wi-Fi for the laptops and graphics cards for the desktop.
class device:
total_devices = 0
self.owner = owner
device.total_devices += 1
def __del__(self):
device.total_devices -= 1
def __str__(self):
return "{}".format(self.name)
def get_total():
return device.total_devices
class laptop(device):
def __str__(self):
class cellular(device):
self.connection = connection
self.BYOD = BYOD
def __str__(self):
print (device1)
print (device2)
print (device.get_total())
Both children contain a __str__ method, even though the parent class
also has one. Through a process called overwriting, if a special method is
called that exists in both the parent and child, than only the child method will
run. In the absence of a called method in a child, the parent will runs its
method instead. This is why referencing a laptop object as a string will
display laptop information, but deleting a laptop object will fall back to the
parent and run its destructor method instead.
Understanding how inheritance works can provide your applications
with unprecedented organization and composition. Most higher-level and
advanced programs take advantage of classes and their properties to quickly
devise a framework for many applications such as database tools, so learning
them would undoubtedly improve your Python skills.
Example Program 7 – project7.py
class house:
self.name = name
self.bedrooms = bedrooms
self.bathrooms = bathrooms
self.cost = 0
class apartment(house):
self.montly_payment = 0
forsale1.montly_payment = 250
Homework program:
Expand the database program that you could optionally create in the
last chapter to include inheritance.
Modules
Every bit of functionality that we have used so far is built-in to Python
already. Python is an expansive language, but additional features can be added
to Python easily through modules. Those familiar with C can relate modules to
“h” files and preprocessor statements. Modules do much the same thing, they
are included in order to add new functions and commands to Python.
To add a new module, we only need to include one statement at the top
of our program.
import math
import math
print (math.sin(3))
answer = math.sqrt(16)
print (answer)
In particular, sqrt(), sin(), and gcd() are three examples you can notice
above. Every module has a defined purpose, and math’s is to provide
advanced mathematical functions. Here is a list of the most important ones.
math.e – 2.71828
Those needing to use complicated functions such as the ones above only
need to “import math” at the top of the program.
current_time = datetime.datetime.now()
print (current_time.hour)
print (current_time.minute)
print (current_time.second)
year
month
day
Or os, a module that unlocks operating system functions for altering files.
Here is a small program for creating a new folder and then making it the active
directory.
import os
And other highly useful modules, such as random, statistics, and pip exist
that can give new features to your Python applications that were not previously
possible. Python also has support for downloading and using user-created
modules, but that is an advanced concept not covered here.
Example Program 8 – project8.py
import random
rng = random.randrange(1, 7)
if (rng == 1):
Homework project:
Create a “sampler” program that shows off various Python module
features.
Common Errors
After every comparison statement and loop (such as if, elif, else, for,
while, def, and class) there is a colon (:). This colon denotes that the next line
should be indented, and thus all indented lines will fall within the function’s
scope. Failure to place a colon returns a syntax error.
Beginners will often try to use functions that are not in Python by default
without including the correct module. Trying to call an advanced math
function, or editing a file directory is not possible with regular Python.
Always place the import commands for modules you will use at the top of the
program, or the application will simply not run.
Thank you again for downloading this beginner’s guide to Python. Now
that you have finished the text, you have a basic knowledge of how Python
works, and you should be able to write your own programs. You can further
increase your knowledge by attempting to create larger and more complicated
programs, or you can study modules and learn new functions. If you have
enjoyed the book, rate and leave a review on Amazon so more high quality
books can be produced.
Hacking University Senior Edition
Linux
BY ISAAC D. CODY
Table of Contents
Introduction
History of Linux
Benefits of Linux
Linux Distributions
Ubuntu Basics
Installing Linux
Managing Directories
Apt
More Terminal Commands
Useful Applications
Administration
Security Protocols
Scripting
I/O Redirection
This document is geared towards providing exact and reliable information in regards to the
topic and issue covered. The publication is sold with the idea that the publisher is not
required to render accounting, officially permitted, or otherwise, qualified services. If
advice is necessary, legal or professional, a practiced individual in the profession should be
ordered.
In no way is it legal to reproduce, duplicate, or transmit any part of this document in either
electronic means or in printed format. Recording of this publication is strictly prohibited
and any storage of this document is not allowed unless with written permission from the
publisher. All rights reserved.
The information provided herein is stated to be truthful and consistent, in that any liability,
in terms of inattention or otherwise, by any usage or abuse of any policies, processes, or
directions contained within is the solitary and utter responsibility of the recipient reader.
Under no circumstances will any legal responsibility or blame be held against the publisher
for any reparation, damages, or monetary loss due to the information herein, either directly
or indirectly.
The information herein is offered for informational purposes solely, and is universal as so.
The presentation of the information is without contract or any type of guarantee assurance.
The trademarks that are used are without any consent, and the publication of the trademark
is without permission or backing by the trademark owner. All trademarks and brands within
this book are for clarifying purposes only and are the owned by the owners themselves, not
affiliated with this document.
Disclaimer
This book will explicate upon the benefits of switching to Linux, as well
as serve as a beginners guide to installing, configuring, and using the most
popular distribution. Then, the terminal command line will be explained to tell
how to take advantage of the OS in ways not possible in other systems. Truly
there are many advantages to be gained by switching to Linux, and you just
might find a suitable primary OS to use on your computers by reading this
book.
History of Linux
Then, 3rd party organizations took the base Linux product and added
their own high level software and features to it, thereby creating Linux
“distributions”. Linux remains a free hobby project even through today, and
thus the kernel is continuously receiving updates and revisions by Torvalds and
the community. Throughout the 2000s, many other 3rd parties saw the
usefulness of the Linux environment and they began to incorporate it into their
production environments and corporations. Today, Linux is known for being
highly used in servers and business settings with a small dedicated desktop
following. Working towards the future, the kernel has reached a level of
popularity where it will never die out. Large companies revel in Linux
because of its advantages and usefulness, and so the kernel and various
distributions will always exist as the best alternative operating system.
Benefits of Linux
First, Linux is free. The background of GNU places Linux into a “free
and open source” mentality where most (if not all) of the software shipping
with Linux is free. Free and open source (FOSS) refers to two things- the
software is both monetarily free and the source code is also transparent. FOSS
differs from proprietary software in that everything is open with FOSS, and
there are no hidden spyware, fees, or catches involved with using it. The
software is often more secure because anybody can contribute to the readily
available source code and make it better. Because Linux and most of the
software you can download for it is free, it is a fantastic operating system for
small businesses or individual users on a budget. Certainly no quality is
sacrificed by not charging a fee, because the Linux project and its various
distributions are community-driven and funded through donations. Compare
this to the cost of Windows, which is often many hundreds of dollars for the
OS alone. Microsoft Office is a popular document writing program suite, but
it also prices high. Free alternatives to these programs exist in Linux, and they
definitely compare in quality to the big name products.
Perhaps the best benefit to using Linux is the speed. Low system
requirements mean that computers that are normally slow and groggy on
Windows will be zippy and quick on Linux. Users frustrated with computer
slowdowns can replace their OS for a more responsive experience.
Furthermore, Linux can be installed on older computers to reinvigorate them.
So even though that old laptop may be too outdated for the newest version of
Windows, there will probably be a distribution of Linux that will squeeze a
few more years of useful life out of it.
Linux Mint is a highly used OS in the Linux world. “Powerful and easy to
use”, Mint contains FOSS and proprietary software as well with the purpose
of being a complete experience for Linux beginners. While not totally Linux-
like, Mint is an excellent choice for a first-time alternate operating system. It
consistently ranks among the most used operating systems ever, and its default
layout is very similar to Windows facilitating a smooth transition into the Linux
world.
Slackware is an OS that goes back even further than Debian. It stays close
to the original Linux intent, meaning that you will have to install your own GUI
and program dependencies. Because of that fact, Slackware is mostly for
intermediate Linux users, as beginners will be confused at the unfamiliar
methods. However, if you want to experience a Linux distribution that is
closer to the UNIX roots, Slackware can provide for you.
Arch Linux is another distribution, but one that is mostly designed for
experienced users. The OS comes as a shell of a system that the user can
customize to their liking, by adding only the programs and services that they
want. Because of this, Arch is difficult to set up, but a rewarding and learning
experience as well. By building your own personal system, you will
understand the deeper Linux concepts that are hidden from you on the higher
level distributions. Install this advanced OS after becoming very comfortable
with the basics.
If you are ready to take the plunge into a Linux based distribution, the
first thing you must do is back up your files. Overwriting the OS on your hard
drive will erase any data contained within, meaning you must back up any
pictures, music, or files you wish to keep after the transition. Use an external
hard drive, or an online data storage site (such as Google Drive) to
temporarily hold your files. We are not responsible for you losing something
important, back it up!
Next we will need to choose an OS. This book will use Ubuntu 16.04 as
an extended example, and it is recommended you do the same. Navigate to
Canonical’s official website (http://www.ubuntu.com) and acquire a copy of
the OS. You will download the image from the site to your computer.
Download a tool for writing the image file. For DVDs install Imgburn
(http://www.imgburn.com/), and for flash media download Rufus
(https://rufus.akeo.ie/). The most common method of OS installation is to use a
4GB USB drive, and it is more recommended. Insert your media, start the
appropriate program, select the OS image that was downloaded, and begin the
writing process. It will take some time, as the image needs to be made
bootable on the media. When it is finished, you can shut down your computer
fully.
This is the point to make double sure you are ready to install Linux.
Check that your files are backed up, understand that you will be erasing your
current OS, and preferably have a Windows/OSX install disc handy in case
you decide to switch back. If you are indeed ready to switch, continue.
With the installation media still inserted, turn on your computer. The
first screen that you will see is the BIOS / UEFI POST screen, and it will give
a keyboard button that you should press to enter setup. This screen shows
every time you boot, but you probably pay no attention to it. Press the
indicated key to enter the BIOS setup. If you are too slow, the screen will
disappear and your usual OS will begin to load. If this happens, simply shut
the computer back down and try again.
Once within the BIOS / UEFI, you will have to navigate to the “boot
order” settings. Every computer’s BIOS / UEFI is slightly different, so we
cannot explain the process in detail. But generally you can follow button
prompts at the bottom of the screen to understand how to navigate. After
arriving at the boot order settings, place your boot medium at the top of the
list. As an example, if you used a USB drive, then you would see its name and
have to bring it to the top of the list. These settings control the order in which
the PC searches for operating systems. With our boot medium at the top of the
list, it will boot into our downloaded Linux image instead of our usual OS.
Save your settings and restart the computer. If everything was done correctly
the computer will begin to boot into Ubuntu.
Primary OS boots instead of Linux – You probably did not save the
settings with your alternate boot medium at the top of the list. The
PC is still defaulting to the internal HDD to boot.
“No boot media found” – Did you “drag and drop” your Linux
image onto the media instead of writing it? Without explicitly
telling the computer it is bootable, it will not know what to do with
the data files on the media. Alternatively, you could have a
corrupted download, or an incomplete write. Try downloading the
image again and making another installation.
But most of those problems are rare or simply due to user error. Linux has
high compatibility and is relatively easy to install/use past the initial
installation. The typical user will have Ubuntu boot successfully at this point,
and they will be presented with a working computing environment.
The desktop you see is referred to as a “Live CD”, which is pretty much a
demonstration of the OS and how it works. You have not actually installed the
OS to your hard drive yet, as it is still running directly from your boot media.
It is a chance for you to test out Linux without actually removing your primary
OS, so take the opportunity to explore how Linux distributions work.
Ubuntu Basics
Furthermore, there is a bar at the top of the screen that works like the
“menu” bar of other operating systems. This is where drop-down menus such
as “file”, “edit”, “help”, etc… will appear once a program is active.
On the desktop, you will see an “Install Ubuntu 16.04 LTS” icon.
Double clicking it will launch an application that makes installation very easy.
If you are not connected to the Internet, do so now by plugging in an Ethernet
cord or by connecting to Wi-Fi from the top right icon. Select your language
and click “continue”. The next prompt will ask whether you would like to
download updates and install third-party software during the OS installation.
These options are highly recommended for beginners, so check them and click
“continue”.
The application will move on to another screen asking for your install
method. There are various options, such as erasing the disk altogether,
installing alongside your primary OS, or updating a previous version of Linux.
Select an option that works best for you. If you are still hesitant about making
a full switch, elect to install Ubuntu as your secondary OS. That option will
allow you to choose which OS to boot into after the BIOS screen.
Nevertheless, select your option and click “install now”.
While Ubuntu installs, you can specify a few other options, such as your
time zone, computer name, account name, and password. The entire
installation should not take too long, but it will take long enough that your
computer should be plugged in (if it is a laptop). After finishing, the OS will
require a reboot. Congratulations, you now have a usable Linux system on
your computer. Throughout the next chapters in this publication we will focus
on Linux concepts, how do achieve certain tasks, and how to further your
knowledge of your system.
Managing Hardware and Software
Directories, another name for folders, work the same as they do in other
operating systems. Folders hold files, and you must be currently accessing a
directory in order to interact with the files inside of it. You can use the
terminal command “cd” to change directory and move about the file system.
As an example, typing “cd Desktop” from the Home folder will transfer you to
that folder. Now using “ls” will not show anything (unless you added files to
the desktop). To back out, type “cd ..”. Practice navigating around the file
system in this fashion; cd into a directory and ls to view the files.
Because you are typing commands, Linux expects your input to be exact.
If you misspell a command it will simply not work, and if you type a folder or
file incorrectly it will try to reference something that does not exist. Watch
your input carefully when using the terminal.
You can also create and remove directories and files through terminal as
well. For this example navigate to the Home directory. As a shortcut you can
type “cd ~” to change the directory to your Home, because the tilde key is short
for “the current user’s home”. Make a directory with the “mkdir” command;
type, “mkdir Programming” to create a new folder with that title. You can CD
into it, or you can go to the GUI and enter it to prove that you have indeed
created a new folder. Now remove that directory by going Home and typing
“rmdir Programming”. Without hesitation, Linux will remove the specified
directory. Similarly, using “rm” will remove the specified file.
Linux has a design philosophy that many users are not used to. In
Windows and OSX, the OS will almost always double check that you want to
commence with an action such as deleting a file or uninstalling a program.
Linux distributions believe that if you are imitating an event, you definitely
mean to follow through with it. It will not typically confirm deleting
something, nor will it display any confirmation messages (file successfully
deleted). Rather, the absence of a message indicates the process completed
successfully. While the philosophy is somewhat dangerous (because you could
potentially ruin your OS installation without warning), it serves as a design
contrast to other operating systems. Linux gives you complete control, and it
never tries to hide anything or obscure options because they might be too
complicated. It takes some time to get used to, but most users agree it is a
welcome change to be respected by the technology they own.
This does not compromise security, however, because any critical action
requires the “sudo” command as a preface. Sudo stands for “super user do”,
meaning that the user of the highest permissions is requesting the following
command. Any sudo entry will require an administrator password, so
malicious software or un-intending keyboard spammers cannot accidently do
damage without knowing the password first. A lot of the commands we use in
this book require sudo permissions, so if the command fails to complete with a
message explaining it does not have enough permissions you can retry with
sudo.
Apt
Learning the terminal opens up computer functions that are not available
through the GUI. Also, you can shorten the amount of time it takes to do many
things by typing it instead. Take, for instance, the amount of work required
installing a program. If you wanted to download the Google Chromium
browser, you would have to open the software center, type in the name of the
program, locate the correct package, mark it for installation, and execute the
action. Compare that to typing “sudo apt-get install chromium-browser” into
the terminal. With that one command, Ubuntu will save you many minutes.
The usefulness of apt extends beyond that, as you can use it to update
every single application on your system with a few commands. Use “apt-get
update” to refresh the repository, then use “apt-get upgrade” to have every
application upgrade itself to the newest version. Windows OS users should be
envious at this easy process, because updating a Windows programs requires
uninstalling and reinstalling with the newest version.
As time goes by, you might need to update the Ubuntu version. Every
year there is a new release, and it can be installed with “apt-get dist-
upgrade”. Staying up to date with the newest fixes and additions ensures your
Linux system will be working healthy for a long time. You might have even
noticed that installing and updating the system does not require a reboot; a
feature that contributes to Linux computer’s lengthy uptimes and stability.
Lastly, removing an application is done with “apt-get remove” followed by the
package name.
To run the programs that we install we can either search for them from
the dash, or we can just type the package name into the terminal. Typing
“chromium-browser” will launch it just the same as double clicking its icon
would. Some programs must be started from the command line by typing the
package name exclusively because the package does not show up in a dash
search. Overall utilizing the terminal is a time-saver and a great way to
practice moving away from slow and cumbersome graphical user interfaces.
Here are a few more basic terminal commands that you should internalize
and put to use in your system. Fully understanding the basics will provide a
decent foundation upon which to build on later.
One of the most useful programs from the command line, nano is a simple
text editor that can be used to edit files and quickly make changes to settings or
scripts. It is accessed by typing “nano” into a command line. You can type a
file as needed and then press ctrl+x to save and quit. As you save, you will
give it the name and file extension associated with it; notes.txt will create a
text file with the name “notes”. Alternatively, you can edit a file by typing
“nano notes.txt”. In that example, we open notes in the editor and display its
contents in an editable state.
Nano may be very simple, but it is undoubtedly powerful and a time saver
for quick changes and file creation.
Connecting to Windows / Mac Computers
[share]
browsable = yes
guest ok = yes
read only = no
Using other operating systems is not complicated when you connect them
together. So long as the computers are on the same network you can create file
shares, join them into a domain, or use a simple service such as Dropbox.
Useful Applications
Here is a list of the best Applications for your Ubuntu system that will help
you get the most out of your computer.
Creativity – Aud
acity, GIMP
And for programs that help with usability, there are so many varied choices
that it depends on what you are trying to accomplish. The best way to discover
a program is to search on the internet for a functionality you wish to add. For
example, if you are searching for a quick way to open and close the terminal
you might come across the program “Guake”. Or if you are wanting audio
within the terminal it might recommend “Cmus”. Finding the perfect
applications for you is part of the customization aspect of Linux, and it makes
every install a little more personal for each user.
Administration
If you are looking for a “Control Panel” of sorts, you can find shortcuts
to administrative tools such as network, printing, keyboard, appearance, and
more from within the “System Settings” application. Some Ubuntu variants use
“Settings Manager” or just “Settings” for the same purpose.
As for services, you might have noticed we use the “service” command
to change their status. So starting a web server would be done with “service
apache2 start”, restarting it done by replacing start with restart, and stopping it
by replacing start with stop. Finding a list of services is done with “service –-
status-all”. Services are daemons, or background tasks that are continuously
running. They can be gathering data, running a service such as Bluetooth and
Wi-Fi, or waiting for user interaction.
Security Protocols
One feature brought over from UNIX is file permissions. Every file has
a set of permission- the owner, group, and rights. The command “chown”
changes the owner of a file, “chgrp” changes the group, and “chmod” changes
the rights associated with the file. Discovering the permissions of a file or
folder is done by typing “ls -l filename”. It will return an initially confusing
line such as “- rw- rw- r--”. “R” means read, “W” stands for write, and the
third option is “X” for execute. The three sets are respectively owner, group,
and other. So our example file above has read and write permissions set for
the owner and its group, but only read permissions for other users. This means
that the owner and the group he belongs to (most likely sudo users) have
permission to both access the file and change its contents, but other users on
the network or PC can only view the contents and not edit it. Script files will
need to have the X in order to be executed, and without it they cannot be run.
Most people will only need to use the “chmod” command to change the
permissions of files they wish to use. We use the command and a set of
numbers to set the permission of the file. “chmod 777 test.sh” makes the file
readable, writable, and executable by all users anywhere because each
specification (owner, group, other) has the number 7 attached to it. Numbers
determine the permissions that entity has, and the number used is calculated
like so:
Security within Linux expands beyond just permissions. Ensure that you
practice good security practices, and that you are following common sense in
regards to security- install only needed programs, do not follow all internet
advice, do not use sudo too often, use passwords, use encrypted networks,
keep software up to date, encrypt important files, and make regular backups.
As a final word of advice, look into using a distribution with SELinux, a
module that supports AC and other security policies.
Scripting
To start a script, create a new file “script.sh” within nano. The first line
must always be “#!/bin/bash” to mark it as a bash script. Type the following
lines for your first script.
read name
echo “Hey, $name. Here is your current directory, followed by the files.”
Pwd
Ls
Scheduling tasks for a certain time can be done with the Cron system
daemon. It is installed be default on some systems, but if not “sudo apt-get
install cron” can be used. Start the service with “service cron start” and create
a new crontab file with “crontab -e”. Select nano as your text editor. At the
bottom of the created file, add a new line with our scheduled task. The format
goes as follows:
minute, hour, day, month, weekday, command
0 12 * * * ~/script.sh
This will run the script.sh found in the Home directory every day at
noon.
30 18 25 12 * /usr/bin/scripts/test.sh
And this will run test.sh within the /usr/bin/scripts directory at 6:30 on
Christmas day every year.
Now extracting that same archive can be done with “tar –xzvf
name.tar.gz”. You will notice that the –c was replaced with an –x, and this
indicates extraction. Once again if you are dealing with bzip2 files use the –j
switch instead.
Continuing with advanced terminal concepts, let us talk about a few
quality tips and tricks that can save you time in the terminal. When typing a
command or file name, press tab halfway through. This feature, tab
completion, will guess what you are attempting to type and fill in the rest of the
phrase. For files it will complete the name as shown in the directory, or
complete a command by considering what you are trying to do. Linux experts
and anyone that has to use the terminal regularly may seem as though they are
typing exactly what they want with extreme accuracy and speed, but they are
actually just using tab completion.
And the most requested terminal tip involves copy and pasting.
Attempting to paste a line into the terminal results in the strange character ^v.
The keyboard shortcut is not configured to work in the terminal, and that is why
the strange combination is displayed. To actually paste, right click and select
the option; or use the key combination shift+insert. Copy in the same way, but
with ctrl+insert instead. While it might be okay to copy and paste terminal
commands from the Internet (provided you understand the risk and know what
they are doing in the command), do not try to paste from this publication. The
formatting introduced through the medium in which you are reading it might
have inserted special characters that are not recognized by the terminal, so it is
best if you do not copy and paste, but rather you should type manually any
commands presented.
Linux has a hidden feature that not many users know about. Files are
displayed to the user when you visit that directory or type ls, but actually not
all of the files are viewable this way. In Linux if you name a file with a period
as the first character it will be marked as hidden. Hidden files are not
normally visible by common users, and it acts as a way to protect configuration
files from accidental editing/deleting/so forth. To see those files, we only need
to add the –a tag to our ls search. In the GUI press ctrl+h in a directory to
reveal the secret content. And as you create scripts and other configuration
files consider hiding them with the period as a form of user protection.
Any command within terminal can be interrupted or quit with the ctrl+d
key combination. Use it to stop a lengthy process or to exit out of a
program/command that you do not understand.
This alias will change the directory to home and display the contents by
typing “gohome”. When creating aliases you must follow the formatting
presented above exactly, meaning there is no space between the command and
the equal sign. Multiple commands are strung together inside the single quotes
separated by “&&”. For more robust aliases, add a function instead. The
following example combines cd and ls into a single command.
function cdls () {
cd "$@" && ls
}
After writing your aliases, save the file and restart the computer. Your
new commands are then available for use.
That file we edit, .bashrc, is the configuration file for the Ubuntu
terminal. Besides making aliases we can also use it to customize our terminal
settings, such as color, size, etc... A quick tip is to uncomment the
“#force_color_prompt=yes” by removing the # and ensuring “yes” is after the
equals. This adds color to the terminal, making certain words different
colors. More options are available when you open a terminal, right click on it,
and select profiles followed by profile preferences. Through the tabs here you
can customize the font, size, colors, background colors, and much more.
Customization of the terminal is recommended if you are going to be using it a
lot, because it helps to be comfortable with the tools you will work with.
I/O Redirection
Input and output are normally direct, but by using I/O redirection we can
do more with the terminal. As an example, the “cat” command (concatenate)
followed by a file will output that file to the screen. Running cat by itself
opens a parser where any line that is input will be immediately output (use
ctrl+d) to quit. But with I/O redirection hotkeys (<, >, <<, >>, |) we can
redirect the output to another source, such as a file. And “cat > test.txt” will
now put the standard output in that new file. Double signs signify appending,
so “cat >> test.txt” will place the output at the end of the file rather than
erasing the contents at the beginning.
The vertical line character, or the “pipe”, uses another form of I/O
redirection to take the output of one command and directly insert it into the
input of another. “ls | sort –r” would take the output of ls and sort it into a
backwards list. We redirected the output and gave it to another command to
accomplish this.
And finally, the “grep” command is used very often within I/O
redirection. Grep can search for a certain string within a specified file and
return the results to standard output. Using redirection, this output can be put
into other commands. An interesting feature of Linux to note is that object is a
file, even hardware. So our CPU is actually a file that stores relevant data
inside of it, and we can use grep and other tools to search within it. That
example is fairly advanced, but here is a simpler instance:
And it will search within the file for that specific word. I/O redirection
can become a complicated process with all of the new symbols and commands,
but it is a feature that you can incorporate into your scripts and daily use that
often allows for certain features and functions of Linux to be done in a single
line.
Linux and the terminal are difficult concepts to fully master. But with
practice and continuing dedication you will be able to perform masterful feats
of computing and do helpful tasks that are not possible in Windows or OSX.
Learning more about commands and how to use them certainly helps in this
regard, so persist in your studies of new commands and their use. Positively
the only command you actually need to memorize is “man”, a command that
will show the manual pages and documentation of any other command
specified. The manual pages show switches, examples, and the intended use of
every command on your system. Use the tool to your advantage and gain
intimate knowledge of your system.
More Linux Information
The “Linux file system” refers to the main layout of the files and folders
on your computer. If you continue to “cd ..” in the terminal, or if you click the
back button on the GUI until it goes no further you will stumble upon the “root”
directory. The folders here, bin, boot, etc, usr, and so on are how your
hardware and settings are configured. Each folder has a specific purpose and
use, and you can understand them by exploring the contents. As an example,
user data is stored in home, but user programs are stored in usr. Because of
how diverse and complicated the file system actually is it will not be
discussed here, but if you wish to learn more do an Internet search or read the
documentation associated with your operating system.
Linux systems are often used for purposes other than desktop use.
Dedicated machines run variants of Linux because of the power and stability it
provides. Even our cars have a Linux kernel running to keep track of error
codes and help mechanics.
And finally, Linux systems are not limited to the interfaces we have seen
insofar. Every distro has its preferred desktop environment, but the interface
can be extremely customized to the individual’s preference. There are even
file and web browsers for the terminal, which is greatly helpful for those using
SSH or remote computing. All-in-all, you should try out different DE’s by
installing them and configuring them to your liking.
What Next and Conclusion
How you continue depends on what you want to do with your Linux
distribution. For casual browsing and simple use, continue with Ubuntu and
install the programs you need. For more adventurous people, consider
installing a new distribution to see what each has to offer. Those wishing to
learn even more deeply about Linux can install one such as Arch or DSL to
build their own unique OS from scratch. Administrators and power users can
install a server version of a distro to build their own Linux network, or they
can consider changing over their environment from other operating systems to
entirely free ones.
Isaac D. Cody is a proud, savvy, and ethical hacker from New York City. After
receiving a Bachelors of Science at Syracuse University, Isaac now works for
a mid-size Informational Technology Firm in the heart of NYC. He aspires to
work for the United States government as a security hacker, but also loves
teaching others about the future of technology. Isaac firmly believes that the
future will heavily rely computer "geeks" for both security and the successes of
companies and future jobs alike. In his spare time, he loves to analyze and
scrutinize everything about the game of basketball.