This module will cover most of the essentials you need to know to get started with Python scripting. Whether you have a background in IT or just starting, this module will attempt to guide you through the process of creating small but useful scripts. Python is one of the most popular scripting languages currently. This makes it a popular choice for automation of everyday tasks or the development of tools.Python is an interpreted language, which means the code itself is not compiled into machine code like C code.There are many ways to execute a piece of Python code. Two of the most frequently used methods are running the code from a .py file and running it directly inside the Python IDLE, Integrated Development and Learning Environment. The file-based way is handy when developing an actual script and the
IDLE way is very useful for quickly testing something small. Let's start with the file-based approach. in this case you have to create a file and write the python code and then call the python. this Linux topic.
now let's try with IDLE. Python's own integrated development environment, directly in our
terminal for quicker prototyping. We launch this by executing the Python
binary without any arguments. just first type python in your terminal and write the function directly. like this.
you can also make variables here. 
We can also import libraries and define functions and classes directly in the IDLE for usage in the same session. To exit the IDLE again, we type exit(0). The number 0 is the return code of the Python process, where 0 means all is OK and a number different from 0 indicates an error. Python executes the code from top to bottom. This is important to keep
in mind when writing Python scripts because Python has no clue what is
further down in the script until it gets to it.
Another method is based on adding the shebang (#!/usr/bin/env python3) in the first line of a Python script. On Unix-based operating systems, marking this with a pound sign and an
exclamation mark causes the following command to be executed along with
all of the specified arguments when the program is called. We can give
the Python script execution rights and execute it directly without
entering python at the beginning on the command line. let see sometimes you may use tools just type python and then the file name . like this
Integers: integer is type of number variable. it's included all number without decimal. like 1-9999........
Booleans: Boolean is a data type that can hold only two values true and false. Booleans are used to control logic, conditions, and flow.
Comments: Comments work the same way in Python as they do in all other languages. they are ignored when the program runs and are only for the developers' eyes. It can sometimes be advisible to use comments to remember what a piece of code does or explain some oddity.
.py files e.g. from the command line or in an Integrated Development Environment, _ is simply just a variable. It is often used as a placeholder for values we do not care about. Coding Style: In Python, variable names follow the snake_case naming convention. This means that variable names should be all lower case initially, and an underscore should separate any potential need for multiple words in the name. While ignoring these naming conventions will not cause any issues for the script - Python could care less about what we call our things - other Python developers may get thrown off if they expect one set of rules but face others.The main point here is that our code should be easy to follow and read.
Conditional Statements and Loops
consistency. Some people prefer two spaces, others 4. Some people prefer a single tab character. first we will try if/else block of code.block of code: block of code: it's same just one more condition comes up. now see this while-loop: it is essential to know how a while-loop works in the first place. A while-loop is a loop that will execute its content (the "block") as long as the defined condition is True. It checks the condition before each iteration. if true it continuesly print. whenever it will find the condition is false it will out of the code. Format Strings
populate the string with values during runtime. A new formatting string was introduced with Python 3.6: the f-string. While a regular string could look something like 'Hello world', an f-string adds an f at the beginning: f'Hello world'.
These particular two strings are of the same value. The benefit of the
f-string, however, is that we can swap out parts of the strings with
other values and variables by enclosing them in a pair of curly braces. like this:while some condition is true, and we know that f'Hello #{counter}' will equal Hello # followed by the number of the iteration - starting at 0 - we are ready to try to execute the code![] is an empty list, and [42] is a list with just one element, the int value 42. When pointing out values inside lists, Python numbers the elements in a list from 0 and upwards. like 0,1,2,3,4,5,6,7,8,9..... but when you count it's negative value than it will be from -1,-2,-3,-4,-5,-6.... than 0 out and count from -1. Positive values counts from the left side first value is 0 and then sequentially but negative values are counted from the right side the last one is -1 and then sequentially.for-each loop/for in: Recall from the previous section that a loop is a block of code that
keeps iterating the contents until some condition is met. This section
will look at one kind of loops often referred to as the "for-each loop".
This is a loop that iterates over each element in some collection of elements and does something for each individual element. The for-each loop is structured this way: first the for keyword, then the variable name we choose, followed by the in keyword and a collection to iterate over
Defining Functions
inner scope of the function - the code inside the function - what is important to note here are the def and return keywords. The def keyword is how we define functions in Python. Following def comes the function name (written in snake_case), input parameters inside the parentheses, and a colon. This first line of a function is called the signature of the function. In Python, the ** symbols mean "power of". If we call power_of(4, 2),
we will get back four-to-the-power-of-two or simply four squared. Now,
where does this result end up? It will end up in one of two places,
depending on what we do: 1) the empty void of nothingness, 2) a
variable. like this.Introduction to Libraries
a module, but it would be great if we could share the code inside this module with other people or reuse it in other projects. A library in programming is in many ways similar to a
library in real life. It is a collection of knowledge that we can borrow
in our projects without reinventing the wheel. Once we import a library, we can use everything inside it, including functions and classes. Some libraries ship along with Python. for example, datetime, literaltool etc.. Let us see what classes and functions the library datetime contains. For that, we will use the built-in function called dir(). likeAs we see, we have to call datetime.datetime.now() to get the current timestamp. We import the library, or module, datetime, which then becomes available to reference by name. This module is also called datetime, which contains a now() function. So to get to the now()
function, we first have to reference the module, then the class, and
finally the function, all "chained together" to speak with dots.
This may become cumbersome and clutter the code, so let us look at alternative ways of importing.
pip is short for "pip installs packages",
a recursive abbreviation (meaning the definition refers to the
abbreviation, and thus circles itself). Very funny indeed. Regardless, pip is the name of the Python module that manages external Python packages. With pip,
we can install, uninstall and upgrade Python packages. Unlike
downloading and installing plugins for a browser or text editor, it is
not common to "go shopping" for Python packages. Some valuable arguments for pip that we will look at are install and--upgrade flag, uninstall and freeze. The install argument lets users install new packages or upgrade existing packages to the latest version (if the --upgrade parameter is provided). The uninstall argument will, as its name suggests, remove the package from the system. Surprisingly the freeze command has nothing to do with halting anything or cheesy police movies. We can call the commands either using pip directly or as a Python module.requirements.txt:: literally requirements.txt, contains a list of all the required packages needed to run the script successfully.The format is quite simple. We would copy save it as a requirements file. However, it is a little
bloated, and we do not need to know or even list the dependencies of the
packages we need.when anyone python3 -m pip install -r requirements.txt This will then go through each of the requirements and install them by selecting the latest available and permitted version.Below is a list of common version comparison operators that we are
highly likely to come across in larger Python projects (read more at PEP 440).
~=: Compatible release clause==: Version matching clause!=: Version exclusion clause<=,>=: Inclusive ordered comparison clause<,>: Exclusive ordered comparison clause===: Arbitrary equality clause.
xyz is vulnerable to exploitation at versions 1.0.4 and lower, we can specify in our requirements file that we need xyz>=1.0.5. The Importance of Libraries
import requests and then use it right away. The two most useful things to know about the requests library are making HTTP requests, and secondly, it has a Session class, which is useful when we need to maintain a certain context during our web activity. let's see an example: Regex
the mighty re module — Python’s built-in tool for regular expressions, aka pattern-matching sorcery. When you write import re, you're unlocking a whole arsenal for searching, extracting, and manipulating strings based on patterns.
🔧 What You Can Do with re
Here are some of the most common and powerful functions:
re.search() >: | Finds the first match of a pattern in a strin |
re.match() >: | Checks if the pattern matches from the beginning of the string |
re.findall() >: | Returns all non-overlapping matches as a list |
re.sub() >: | Replaces matches with a new string |
re.split() >: | Splits a string by the pattern |
re.compile() >: | Pre-compiles a regex pattern for reuse |
Managing Libraries in Python
site-packages directory. This is
true for Windows systems, however on Debian and Debian-based systems
such as Kali, Parrot, and Ubuntu, the external libraries are located
inside a dist-packages location. However, the principle is the same. The default site-packages/dist-packages locations are the following:- Windows 10:
PYTHON_INSTALL_DIR\Lib\site-packages: - Linux:
/usr/lib/PYTHON_VERSION/dist-packages/:
The reason why packages are located inside a dist-packages rather than a site-packages directory on Debian-based systems stems from how Debian-based systems handle packages installed with the package manager (apt). However, for simplicity's sake, we will use the common name of site-packages
going forward. If we take a look inside this directory, we will see
many packages available for Python. A package in all its simplicity is
just a folder with at least an __init__.py file inside of it and optionally (although nearly always) other python files and nested folder structures.
Instead of producing a fully functional script for scraping words off a
website, we decided to write the script as an API. We could package the
script together with an __init__.py file (even an empty one
is fine) and place the package inside the site-packages directory.
Python already knows to check this location when searching for packages.
This is not always practical. However, we can tell Python to look in a
different directory before searching through the site-packages directory
by specifying the PYTHONPATH environment variable. As we can see below, without having set a PYTHONPATH environment variable, the search path includes only the standard directories:
Now let's specify a PYTHONPATH environment variable and see how it affects the search path:
PYTHONPATH=/tmp/ python3
Since we set the PYTHONPATH to the root directory, this
has been prepended to the search path. This means two things: first of
all, the packages that exist at the /tmp/ location can now
be imported and used in the project or IDLE, and secondly, it means we
can highjack other packages, changing the behavior. The latter point is a
bonus if we can control the PYTHONPATH of a system to
include our malicious package. We will mainly use the search path to
specify where to find our APIs in everyday development scenarios.
Suppose we wanted to have the packages installed in a specific
folder. For example, we wanted to keep all packages related to us inside
some /var/www/packages/ directory. In that case, we can have pip install the package and store the content inside this folder with the --target flag, like so:
Virtual Environments
So far, we have looked at installing packages onto the local machine,
making packages available to all scripts in our system. If we, for one
reason or the other, need to use one specific version of a package for
one project and another version of the same package for another project,
we will face problems. One solution for this kind of isolation of
projects is using virtual environments or venv for short. The venv
module allows us to create virtual environments for our projects,
consisting of a folder structure for the project environment itself, a
copy of the Python binary and files to configure our shell to work with
this specific environment. Next up, we can source the activate script located in academy/bin/. This configures our shell by setting up the required environment variables so that when we, for example, run pip install requests, we will be using the Python binary that was copied as part of creating the virtual environment, There are many ways to achieve the same goal. We have looked at some of
them, and they will get us very far; however, there are better tools and
solutions for larger or more permanent projects. Say we developed a
custom C2 (Command & Control) in Python
and needed a reliable and separate environment to host the server in.
Virtual environments will likely work fine, but an alternative is to use
container software such as Docker or even a fully isolated
Virtual Machine. For larger software projects in Python, virtual
environments might be pleasing for parts of the way. Additionally,
package- and environment management software such as Conda
will allow greater control of the project, especially when
collaborating with others. These technologies and methodologies are
worthy of their own modules.
















0 Comments
Thanks For your comment