هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.
$ مستخدم عادي# بصلاحية root (أو مع sudo)
Use lists
A list keeps items in order and can change.
hosts = ["web1", "web2"]
hosts.append("db1")
hosts.extend(["cache1", "cache2"])
hosts.remove("web2")
print(hosts[0], hosts[-1], hosts[1:3], len(hosts))
print(sorted(hosts), "db1" in hosts)
for h in reversed(hosts):
print(h)Use dictionaries
A dict maps keys to values — like a config file or a JSON object.
server = {"name": "web1", "ip": "10.30.1.4", "ports": [80, 443]}
server["os"] = "RHEL 10"
print(server["ip"], server.get("owner", "unknown"))
for key, value in server.items():
print(f"{key:>6}: {value}")
inventory = {
"web": ["web1", "web2"],
"db": ["db1"],
}
inventory.setdefault("cache", []).append("cache1")
print(inventory)تذكّر
d["key"] fails when the key is missing; d.get("key", default) does not.
Use sets and tuples
A set has no duplicates and is fast for "is it in?". A tuple is a list that can not change.
allowed = {"22/tcp", "443/tcp"}
open_now = {"22/tcp", "443/tcp", "3306/tcp"}
print("unexpected:", open_now - allowed)
print("both:", open_now & allowed)
point = ("web1", 443)
host, port = pointHandle strings
Strings have many built-in methods; f-strings put values inside.
line = " Oct 27 12:44:01 server1 sshd[6731]: Failed password for root from 203.0.113.50 "
clean = line.strip()
print(clean.lower().startswith("oct"))
parts = clean.split()
print(parts[4], parts[-1])
print(", ".join(["a", "b", "c"]))
print(clean.replace("root", "ROOT"))
print(f"{'host':<10}|{'state':^8}|{3.14159:.2f}")| Method | Does |
|---|---|
strip(), lstrip(), rstrip() | Remove spaces at the ends |
split(sep), join(list) | Cut into a list / glue a list together |
startswith, endswith, in | Test text |
replace(a, b) | Replace text |
lower(), upper() | Change case |
Write comprehensions
Build a new list or dict from another one in one line.
ports = [22, 80, 443, 3306, 8080]
web_ports = [p for p in ports if p in (80, 443, 8080)]
squares = {p: p * p for p in ports}
names = ["Web1", "DB1"]
lower = [n.lower() for n in names]
total = sum(len(n) for n in names)Count and group with collections
Counter counts things; defaultdict groups them — perfect for logs.
from collections import Counter, defaultdict
ips = ["203.0.113.50", "198.51.100.7", "203.0.113.50"]
print(Counter(ips).most_common(1))
by_user = defaultdict(list)
for user, ip in [("root", "1.2.3.4"), ("admin", "5.6.7.8"), ("root", "9.9.9.9")]:
by_user[user].append(ip)
print(dict(by_user))