Python is a versatile, high-level scripting language that excels in system automation, administration, and shell scripting. Unlike traditional shell scripts, Python brings power, readability, and a comprehensive standard libraryβmaking it a great choice for automating routine tasks, managing systems, and interacting with the file system and shell environment. In this document, we will explore how to use Python for shell scripting and system administration tasks.
Python syntax is clear and concise, which makes scripts easier to write, review, and maintain compared to Bash or batch scripts.
Python runs on Linux, Windows, and macOSβscripts written on one OS often work on others with minimal modifications.
Modules like os, sys, subprocess, and pathlib provide powerful tools without external dependencies.
As script complexity grows, Python scales seamlesslyβsupporting modularity, error handling, and testing.
#!/usr/bin/env python3
import os
def greet():
print("Hello from Python shell script!")
if __name__ == "__main__":
greet()
Save as greet.py, then:
chmod +x greet.py
./greet.py
#!/usr/bin/env python3
import argparse
parser = argparse.ArgumentParser(description="Greet someone.")
parser.add_argument("name", help="Name of the person")
parser.add_argument("-t", "--times", type=int, default=1, help="Number of times to greet")
args = parser.parse_args()
for i in range(args.times):
print(f"Hello, {args.name}!")
import os
directory = "/var/log"
for filename in os.listdir(directory):
print(filename)
from pathlib import Path
path = Path("/tmp/myfolder")
path.mkdir(exist_ok=True)
file = path / "log.txt"
file.write_text("Log entry")
for child in path.iterdir():
print(child.name, child.stat().st_size)
from pathlib import Path
path = Path(".")
for file in path.rglob("*.py"):
print(file)
import os
import time
stat = os.stat("greet.py")
print("Size:", stat.st_size)
print("Last modified:", time.ctime(stat.st_mtime))
import subprocess
result = subprocess.run(["ls", "-l", "/tmp"], capture_output=True, text=True)
print(result.stdout)
try:
subprocess.run(["ls", "/nonexistent"], check=True)
except subprocess.CalledProcessError as err:
print("Command failed with code", err.returncode)
result = subprocess.run(["ps", "aux"], capture_output=True, text=True)
lines = result.stdout.splitlines()
for line in lines[:5]:
print(line)
import psutil
for proc in psutil.process_iter(['pid', 'name', 'memory_info']):
print(proc.info)
print("CPU usage:", psutil.cpu_percent(interval=1))
print("Memory:", psutil.virtual_memory())
print("Disk usage:", psutil.disk_usage("/"))
print("Network IO:", psutil.net_io_counters())
import zipfile
from pathlib import Path
def backup_dir(src, dest_zip):
with zipfile.ZipFile(dest_zip, 'w', zipfile.ZIP_DEFLATED) as zf:
for file in Path(src).rglob("*"):
zf.write(file, file.relative_to(src))
backup_dir("/home/user/data", "/home/user/data_backup.zip")
import os
import time
log_dir = "/var/log/myapp"
now = time.time()
for file in os.listdir(log_dir):
path = os.path.join(log_dir, file)
if os.stat(path).st_mtime < now - 7 * 86400:
os.remove(path)
# Edit crontab
crontab -e
# Add line to run daily
0 2 * * * /usr/bin/env python3 /home/user/scripts/backup.py
import schedule
import time
def backup():
print("Running backup...")
schedule.every().day.at("02:00").do(backup)
while True:
schedule.run_pending()
time.sleep(60)
import shutil
total, used, free = shutil.disk_usage("/")
if free / total < 0.1:
print("Warning: Low disk space!")
import smtplib
from email.mime.text import MIMEText
def send_alert(subject, body):
msg = MIMEText(body)
msg["Subject"] = subject
msg["From"] = "admin@example.com"
msg["To"] = "you@example.com"
with smtplib.SMTP("smtp.example.com") as s:
s.send_message(msg)
send_alert("Low disk", "Disk free space below 10%")
import pwd
for u in pwd.getpwall():
print(u.pw_name, u.pw_uid, u.pw_gecos)
import os
import stat
mode = os.stat("/etc/passwd").st_mode
print("Readable by others:", bool(mode & stat.S_IROTH))
import subprocess
subprocess.run(["sudo", "systemctl", "restart", "apache2"])
import configparser
config = configparser.ConfigParser()
config.read("app.ini")
db_host = config["database"]["host"]
Python is commonly used for developing websites and software, task automation, data analysis, and data visualisation. Since it's relatively easy to learn, Python has been adopted by many non-programmers, such as accountants and scientists, for a variety of everyday tasks, like organising finances.
Learning Curve: Python is generally considered easier to learn for beginners due to its simplicity, while Java is more complex but provides a deeper understanding of how programming works.
The point is that Java is more complicated to learn than Python. It doesn't matter the order. You will have to do some things in Java that you don't in Python. The general programming skills you learn from using either language will transfer to another.
Read on for tips on how to maximize your learning. In general, it takes around two to six months to learn the fundamentals of Python. But you can learn enough to write your first short program in a matter of minutes. Developing mastery of Python's vast array of libraries can take months or years.
6 Top Tips for Learning Python
The following is a step-by-step guide for beginners interested in learning Python using Windows.
Best YouTube Channels to Learn Python
Write your first Python programStart by writing a simple Python program, such as a classic "Hello, World!" script. This process will help you understand the syntax and structure of Python code.
The average salary for Python Developer is βΉ5,55,000 per year in the India. The average additional cash compensation for a Python Developer is within a range from βΉ3,000 - βΉ1,20,000.
Copyrights © 2024 letsupdateskills All rights reserved