Zum Hauptinhalt springen
Intelligence View
⚡ tsecurity.de Intelligence

Bash script vs Python script for sysadmin tasks?

Which do you prefer to sling around, a bash command or a python script? In my goal to write more python and less shell, for the benefit of my colleagues'…

Beitrag
0
Seite
0
↗ Quelle (dev.to)
Quelle & Fakten · 4 Min. Lesezeit
Quelle: dev.to
Rubrik: Programmation sécurisée

Which do you prefer to sling around, a bash command or a python script?



In my goal to write more python and less shell, for the benefit of my colleagues' sanity, I have been trying to favour Python - specifically, readable and maintainable python.



I have moaned before about how sysadmin scripts often look very messy and unmaintainable, and I have found a perfect example of how that arises.



I needed my team to send me the hostnames, IPs and MAC addresses of their VMs to send to IT for reserving in DHCP, and I started cooking up a python script. Just as I was finishing, I had a flash of inspiration and thought... can't I do just a one-liner in shell?



It's just a matter of getting the default IP and looking for the interface that uses it... I wrote the scirpt so that it could give result for a local host, or a series of specified remote hosts.



Which would you prefer to commit to a tooling repo? :-)



Here's the python script, idiomatic, and hopefully easy to read and maintain. I was going to tell my colleagues "Please clone (script repo) and run the script, supplying the hosts as arguments, like 'gather-ips.py jack@machine1 jack@machine2 ...' (yeah, I would need to send instructions too)




#!/usr/bin/env python

import re
import subprocess
import sys

class SubprocessError(Exception):
pass


def run(command:list[str]) -> str:
proc = subprocess.Popen(command, stdout=subprocess.PIPE, text=True)
stdout, _ = proc.communicate()
if proc.returncode > 0:
raise SubprocessError(f"Failed {command}, see stderr.")

return stdout


def read_ipa(ipa_lines):
ipa_entries = {}

current = None

for line in ipa_lines:
m = re.match(r"^[0-9]+:\s+(\S+?):.*", line)
if m:
current = m.group(1)
ipa_entries[current] = {}
continue
if current is None:
continue

current_entry = ipa_entries[current]

eth_m = re.match(r".+link/ether ([a-fA-F0-9:]+)", line)
if eth_m:
current_entry["mac"] = eth_m.group(1)

inet_m = re.match(r"\s+inet ([0-9.]+)/[0-9]+", line)
if inet_m:
current_entry["ipv4"] = inet_m.group(1)

return ipa_entries


def get_default_ip(ipr_lines):
default_line = [line for line in ipr_lines if 'default via' in line][0]
return re.findall(r"src [0-9.]+", default_line)[0][4:]


def get_ipra_lines(host):
if host:
lines = run(["ssh", host, "ip r; echo ===; ip a"]).split("\n")
idx = 0
for n in range(len(lines)):
if lines[n] == "===":
idx = n
break
ipr_lines = lines[:idx]
ipa_lines = lines[idx+1:]
else:
ipr_lines = run(["ip", "r"]).split("\n")
ipa_lines = run(["ip", "a"]).split("\n")

return ipr_lines,ipa_lines


def ublat(host_string:str):
try:
i = host_string.index("@")
return host_string[i+1:]
except ValueError:
return host_string


def get_target(host=None):
ipr_lines, ipa_lines = get_ipra_lines(host)
entries = read_ipa(ipa_lines)
def_ip = get_default_ip(ipr_lines)
hostname = ublat(host) if host else run(["hostname"]).strip()

for _, data in entries.items():
if def_ip in data.get("ipv4", ""):
print(f"{hostname}\t{data.get('ipv4')}\t{data.get('mac')}")
return
print(f"# Nothing in {entries}")


def main():
if not sys.argv[1:] or "get" in sys.argv[1:]:
get_target()
return

for host in sys.argv[1:]:
get_target(host)


main()






For sake of comparison, this is its bash equivalent - it does EXACTLY the same thing:




command="echo \"\$(hostname)  \$(ip a|grep \"\$(ip r|grep 'default via'|grep -Po '(?<=src )[0-9.]+')\" -B 1|grep -Po '(?<=ether |inet )(\S+)')\"|xargs echo"

if [[ -z "$*" ]]; then
bash -c "$command"
exit
fi

for
node in "$@"; do
ssh "$node" "$command"
done






In the end, I sent a message to the team and told them:




Hi all,



Please run this on each of your VMs and send me the output via email



echo "$(hostname) $(ip a|grep "$(ip r|grep 'default via'|grep -Po '(?<=src )[0-9.]+')\" -B 1|grep -Po '(?<=ether |inet )(\S+)')"|xargs echo




A one-liner in a single message. No sending scripts around. No instructing to clone and execute. Just "run this on each machine."



Which approach would you have taken

Social ReaktionenReagiere als Erste:r — dein Feedback zählt!
Informations-Bewertung:
✏️ Information ergänzen
🛡️ Versioniert via CMS-Revisions-Engine (Freigabe-Queue für Gäste)

💬 Discussion communautaire et commentaires

🌐 Rejoindre le chat principal

Lancez la discussion dans le flux diffusé du Social Chat ou proposez ci-dessus une contribution experte via le formulaire de complément.

Briefing sécurité Gratuit · désabonnement en 1 clic

Intelligence Digest — gratuit

Chaque jour, les principales actualités sécurité · résiliable à tout moment

Évaluation communautaire &amp; preuve sociale
⭐ Avis des lecteurs
–
Ø / 5.0
Pas encore d'évaluation des lecteurs
Cet article vous a-t-il été utile ?
0
Donner votre évaluation
Évaluation détaillée (facultatif)
Contenu & qualité
Source & fiabilité
Actualité

Groupes d’histoires apparentées & sources (IA vectorielle)

6 Cluster
21 sources
CVE-2026-129373 | Joomla! Project Joomla Extension 1.6.0-5.4.10/6.0.0-6.2.0 Password Reset session expiration (EUVD-2026-134294)
VulDB Updates il y a 29 min.
20 autres sources
VulDB Updatesil y a 29 min.CVE-2026-129385 | Joomla! Project Joomla! Extension 4.0.0-5.4.10/6.0.0-6.2.0 Mail Template information disclosure (EUVD-2026-134295) VulDB Updatesil y a 29 min.CVE-2026-129381 | Joomla! Project Joomla Extension up to 5.4.10/6.2.0 Install From Web cross-site request forgery (EUVD-2026-134293) VulDB Updatesil y a 29 min.CVE-2026-127299 | Joomla! Project Joomla Extension up to 1.6.0/5.4.10/6.0.0/6.2.0 com_newsfeeds name cross site scripting (EUVD-2026-134290) VulDB Updatesil y a 29 min.CVE-2026-123210 | Joomla! Project Joomla Extension 4.0.0-5.4.10/6.0.0-6.2.0 com_media input validation (EUVD-2026-134291) VulDB Updatesil y a 19 min.CVE-2026-126045 | Joomla! Project Joomla Extension up to 1.6.0/5.4.10/6.0.0/6.2.0 Language Parameter language file inclusion (EUVD-2026-134289) VulDB Updatesil y a 19 min.CVE-2026-129387 | Joomla! Project Joomla! CMS Extension 4.0.0-5.4.10/6.0.0-6.2.0 com_menus privileges management (EUVD-2026-134288) VulDB Updatesil y a 19 min.CVE-2026-127300 | Joomla! Project Joomla CMS Extension 4.3.0-5.4.10/6.0.0-6.2.0 com_guidedtours cross site scripting (EUVD-2026-134285) VulDB Updatesil y a 19 min.CVE-2026-127295 | Joomla! Project Joomla Extension 4.0.0-5.4.10/6.0.0-6.2.0 Webservice Endpoints permission (EUVD-2026-134286) VulDB Updatesil y a 19 min.CVE-2026-129383 | Joomla! Project Joomla Extension 6.2.0 SMTP OAuth2 Settings information disclosure (EUVD-2026-134287) VulDB Updatesil y a 19 min.CVE-2026-129382 | Joomla! Project Joomla Extension up to 5.4.10/6.2.0 com_media permission (EUVD-2026-134284) VulDB Updatesil y a 19 min.CVE-2026-127297 | Joomla! Project Joomla 3.6.0-5.4.10/6.0.0-6.2.0 Formatted Text Logger race condition (EUVD-2026-134282) VulDB Updatesil y a 19 min.CVE-2026-129389 | Joomla! Project Joomla Extension up to 3.8.3/5.4.10/6.0.0/6.2.0 Wrapper cross site scripting (EUVD-2026-134283) VulDB Updatesil y a 19 min.CVE-2026-127296 | Joomla! Project Joomla CMS Extension 4.0.0-5.4.10/6.0.0-6.2.0 com_config information disclosure (EUVD-2026-134281) VulDB Updatesil y a 1 hCVE-2026-127298 | Joomla! Project Joomla Extension up to 1.6.0/5.4.10/6.0.0/6.2.0 com_contact name cross site scripting (EUVD-2026-134302) VulDB Updatesil y a 1 hCVE-2026-129368 | Joomla Extension 1.6.0-5.4.10/6.0.0-6.2.0 Banner cross site scripting (EUVD-2026-134300) VulDB Updatesil y a 1 hCVE-2026-129386 | Joomla! Project Joomla Extension 1.6.0-5.4.10/6.0.0-6.2.0 com_contact privileges management (EUVD-2026-134301) VulDB Updatesil y a 1 hCVE-2026-129388 | Joomla! Project Joomla! Extension 4.0.0-5.4.10/6.0.0-6.2.0 com_media path traversal (EUVD-2026-134298) VulDB Updatesil y a 1 hCVE-2026-127304 | Joomla Extension 3.9.0-5.4.10/6.0.0-6.2.0 Custom Fields showon cross site scripting (EUVD-2026-134299) VulDB Updatesil y a 1 hCVE-2026-123214 | Joomla! Project Joomla Extension 4.0.0-5.4.10/6.0.0-6.2.0 Web Installer missing authentication (EUVD-2026-134297) VulDB Updatesil y a 1 hCVE-2026-129365 | Joomla! Project Joomla Extension up to 2.5.10/5.4.10/6.0.0/6.2.0 com_installer cross site scripting (EUVD-2026-134296)
13 sources
Square POS Black Friday deals: save up to $291 on three small business systems at Best Buy
Latest from TechRadar il y a 17 min.
12 autres sources
13 sources
ZDI-26-1078: llama.cpp GGUF File Parsing MINICPM-V Heap-based Buffer Overflow Remote Code Execution Vulnerability
ZDI: Published Advisories il y a 14 h
12 autres sources
ZDI: Published Advisoriesil y a 14 hZDI-26-1071: llama.cpp GGUF File Parsing Integer Overflow Remote Code Execution Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1077: llama.cpp GGUF File Parsing HunyuanVL Heap-based Buffer Overflow Remote Code Execution Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1076: llama.cpp Multimodal GGUF File Parsing Out-Of-Bounds Write Remote Code Execution Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1075: llama.cpp GGUF File Parsing set_swa_pattern Heap-based Buffer Overflow Remote Code Execution Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1073: llama.cpp MTMD Multimodal GGUF File Parsing Out-Of-Bounds Read Denial-of-Service Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1074: llama.cpp GGUF File Parsing GEMMA4A Heap-based Buffer Overflow Remote Code Execution Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1072: llama.cpp GGUF File Parsing Integer Overflow Denial-of-Service Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1056: (0Day) PyTorch Foundation PyTorch PT2 File Parsing Exposed Dangerous Method Remote Code Execution Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1048: (0Day) Soda PDF Desktop PDF File Parsing Memory Corruption Remote Code Execution Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1050: (0Day) Soda PDF Desktop PDF File Parsing Memory Corruption Remote Code Execution Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1052: (0Day) PyTorch Foundation PyTorch PT2 File Parsing Code Injection Remote Code Execution Vulnerability ZDI: Published Advisoriesil y a 14 hZDI-26-1049: (0Day) Soda PDF Desktop PDF File Parsing Out-Of-Bounds Write Remote Code Execution Vulnerability
Articles similaires
🔍 Verwandte News

Auch interessante Nachrichten Bash script vs Python script for sysadmin tasks?

Thematisch verwandte Begriffe: Bash, script, Python, sysadmin · 6 Treffer

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

Laden...

Chargement des articles ...

Laden...

Chargement des vidéos ...

💬 Chargement des commentaires…
Sentinel CTI: ONLINE
Tirer pour actualiser
Widgets & Topics
Loading widgets…
Nächster Beitrag