0% found this document useful (0 votes)
249 views

Python C2 Week1

This document summarizes key aspects of Python including: - Python can be interpreted or compiled, with interpreted being more portable but slower. Popular compiled languages include C and C++. - The Python standard library and external modules from PyPI (Python Package Index) provide many reusable functions. Modules are installed via Pip. - Automating tasks with scripts can save time compared to manual work, but scripts require maintenance over time. - Example scripts are shown to check disk usage, CPU usage, network connectivity using modules like shutil, psutil, and requests. The scripts import functions to check system resources and network status before reporting results.

Uploaded by

June Zamora
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
249 views

Python C2 Week1

This document summarizes key aspects of Python including: - Python can be interpreted or compiled, with interpreted being more portable but slower. Popular compiled languages include C and C++. - The Python standard library and external modules from PyPI (Python Package Index) provide many reusable functions. Modules are installed via Pip. - Automating tasks with scripts can save time compared to manual work, but scripts require maintenance over time. - Example scripts are shown to check disk usage, CPU usage, network connectivity using modules like shutil, psutil, and requests. The scripts import functions to check system resources and network status before reporting results.

Uploaded by

June Zamora
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 6

Python C2 Week1

 OS
o Kernel –Core, we don’t interact talaga
o User Space – where we interact directly, everything aside from kernel
 Python Standard Library
 External Modules
 PyPI > Package Index
 Pip, manage external modules
 Compiled language, Compiler translates code to machine level language (C,
C++, etc), specific kung saan talaga
 Interpreted language, doesn’t need compiler to interpret but slower, can
use in different OS
 Java and C# > mixed
 Command Prompt
 cat filename.py > open file
 python 3 filename.py> use file
or
 use shebang tells OS what command we will use in executing that file ie.
nano
o nano filename.py > another open window with file commands> type
above the “#!/usr/bin/env python 3”
o make file executable by using chmod >> chmod +x filename.py >
now you can prefix it by “ ./filename.py”

 Code Reuse

Create Our Own Module


 Example use area module
o cat areas.py //displays code
o may import math ditto
o >> python3
o >> import areas
o >>areas.triangle(3,5)// we used dot notation to access a function
inside
 Submodule if sobrang complex
o Create directories with different modules
o >> ls –l /usr/lib/python3/dist-packages/re
o >> ls –l /usr/lib/python3/dist-packages/requests
o Dapat may init.py file to be recognized as a python module
 IDE – integrated Development Env., may extra functions and features for
easier programming
o Ie Vim w/c includes text highlighting, >> vim areas.py
o >> atom areas.py

 Scalability
 Centralizing mistakes

PITFALLS OF AUTOMATION
 Time to write script < (time to perform manually*amt done)
 Critical datas?
 Pareto principle, 20% of system adm tasks that you perform are responsible
for 80% of your work. Identify those 20%
 Bit-rot > software falling out of step, program notifications if fail or restore
data date added backup

Examples
 import shutil for disk usage
 import psutil for cpu usage
 created C2W1 file in pycharm to create health disk checker
QWIKLABS
 VM (Virtual Machine), simulated comp through software
 SSH > interact with remote linux comp
 Accessig VM
o Use PuTTY Secure Shell (SSH) client to connect to a VM’s external IP ,
so download PPK Format
o In PuTTY, Fill in student_id@ip_address > Expad SSH> Auth > Browse
File for authentication using the PPK File > Open
 Fix File Permissions
o cd scripts > to navigate scripts directory
o ls > list file
o cat health_checks.py > view file
o The shutil module offers a number of high-level operations on files
and collections of files. In particular, it provides functions that
support file copying and removal. It comes under Python's standard
utility modules. disk_usage() method is used to get disk usage
statistics of the given path. This method returns a named tuple with
the attributes total, used, and free. The total attribute represents the
total amount of space, the used attribute represents the amount of
used space, and the free attribute represents the amount of available
space, in bytes.
o psutil (Python system and process utilities) is a cross-platform library
for retrieving information on the processes currently running and
system utilization (CPU, memory, disks, network, sensors) in Python.
It's useful mainly for system monitoring, profiling, limiting process
resources, and managing running processes. cpu_percent() returns a
float showing the current system-wide CPU use as a percentage.
When the interval is 0.0 or None (default), the function compares
process times to system CPU times elapsed since the last call,
returning immediately (non-blocking). That means that the first time
it's called it will return a meaningful 0.0 value. When the interval is >
0.0, the function compares process times to system CPU times
elapsed before and after the interval (blocking).
o This script begins with a line containing the #! character combination,
which is commonly called hash bang or shebang and continues with
the path to the interpreter.
o #!/usr/bin/env python3 uses the operating system env command,
which locates and executes Python by searching the PATH
environment variable. Unlike Windows, the Python interpreter is
usually already in the $PATH variable on linux, so you don't have to
add it.
o sudo chmod +x filename.py > to execute permission and use
./filename.py
o nano filename.py > edit and open nano
o Code:

#!/usr/bin/en
v python3
import shutil
import psutil

def check_disk_usage(disk):
du = shutil.disk_usage(disk)
free = du.free / du.total * 100
return free > 20

def check_cpu_usage():
usage = psutil.cpu_percent(1)
return usage < 75

if not check_disk_usage("/") or not check_cpu_usage():


print("ERROR!")
else:
print("Everything is OK!")

o Requests is a Python module that you can use to send all kinds of
HTTP requests. It's an easy-to-use library with a lot of features
ranging from passing parameters in URLs to sending custom headers
and SSL verification. You can add headers, form data, multi-part files,
and parameters with simple Python dictionaries.You can then access
the response data using the same request. Used to make if the comp
can make calls or requests to the internet. Install it first
 sudo apt istall python3-requests
o Socket Module > all about getting host names and addresses etc.
o Code below:

#!/usr/bin/en
v python3
import requests
import socket

def check_localhost():
localhost = socket.gethostbyname('localhost')
return localhost == '127.0.0.1'

def check_connectivity():
request = requests.get("http://www.google.com")
return request.status_code == 200

o Import the check connectivity and local host to disk checking code:

#!/usr/bin/en
v python3
from network import *
import shutil
import psutil
def check_disk_usage(disk):
"""Verifies that there's enough free space on disk"""
du = shutil.disk_usage(disk)
free = du.free / du.total * 100
return free > 20
def check_cpu_usage():
"""Verifies that there's enough unused CPU"""
usage = psutil.cpu_percent(1)
return usage < 75
# If there's not enough disk, or not enough CPU, print an
error
if not check_disk_usage('/') or not check_cpu_usage():
print("ERROR!")
elif check_localhost() and check_connectivity():
print("Everything ok")
else:
print("Network checks failed")

You might also like