الفلاتر
طريقة البحث
  • الكلمات العادية تجد الأسماء والنصوص والأمثلة.
  • "كلمتان" تجد العبارة بالضبط.
  • --name أو -x تجد خيارًا.
  • #كلمة تبحث داخل الأوامر فقط.
  • @grep تجد الدروس والمعامل التي تستخدم grep.
  • الفلاتر: cat:network · in:labs · level:rhcsa · ch:8 · root:yes. ضع ! قبل كلمة لاستبعادها. OR بين الكلمات تعني إحداها.
  • ↑ ↓ للتنقل · Enter للفتح · Esc للإغلاق · / للبحث

الفصل 2الاسم في الدورة: Data structures

Work with lists, dictionaries and strings

Admin data is lists (of servers, of lines) and key/value pairs (settings, JSON from APIs). Python's lists, dictionaries, sets and strings — plus comprehensions — handle almost every case.

  • 6 الدروس
  • 0 الأوامر

هذا الجزء لم يُترجم بعد. أنت ترى النص الإنجليزي.

$ مستخدم عادي# بصلاحية root (أو مع sudo)

2.1

Use lists

A list keeps items in order and can change.

lists.py
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)

2.2

Use dictionaries

A dict maps keys to values — like a config file or a JSON object.

dicts.py
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.

2.3

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.

sets.py
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 = point

2.4

Handle strings

Strings have many built-in methods; f-strings put values inside.

strings.py
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}")
MethodDoes
strip(), lstrip(), rstrip()Remove spaces at the ends
split(sep), join(list)Cut into a list / glue a list together
startswith, endswith, inTest text
replace(a, b)Replace text
lower(), upper()Change case

2.5

Write comprehensions

Build a new list or dict from another one in one line.

comprehensions.py
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)

2.6

Count and group with collections

Counter counts things; defaultdict groups them — perfect for logs.

count_ips.py
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))