commit message from python script
This commit is contained in:
66
Lehrer/pythonkurs/Mittwoch/print_ip
Executable file
66
Lehrer/pythonkurs/Mittwoch/print_ip
Executable file
@@ -0,0 +1,66 @@
|
||||
#! /usr/bin/env python3
|
||||
|
||||
import os
|
||||
import sys
|
||||
import re
|
||||
|
||||
from utilities import hide_exception
|
||||
|
||||
|
||||
def read_from_command(command: str) -> list:
|
||||
# command = "tar cf /tmp/backup.tar ."
|
||||
# ret = os.system(command)
|
||||
# ret = [8 Bit Exit code] + [8 Bit Flags]
|
||||
# exit_code = ret >> 8
|
||||
|
||||
try:
|
||||
with os.popen(command, 'r') as pipe:
|
||||
return [l.rstrip() for l in pipe.readlines()]
|
||||
except OSError:
|
||||
print("Kann Programm nicht auslesen", file=sys.stderr)
|
||||
# zur Sicherheit auch hier eine Liste zurueckgeben
|
||||
return []
|
||||
|
||||
|
||||
def extract_ip(lines: list) -> list:
|
||||
# [0-9] 1 Zeichen aus der Gruppe 0 bis 9 (\d)
|
||||
# regex{1,3} regex matcht 1 bis 3 mal
|
||||
# \. 1 echter Punkt
|
||||
# . 1 beliebiges Zeichen
|
||||
# regex? regex match 0 oder 1 mal
|
||||
# regex+ regex match 1 mal oder beliebig oft
|
||||
# regex* regex match 0 mal oder beliebig oft
|
||||
# regex{3} regex match exakt 3 mal
|
||||
# (regex) Gruppierung des Teil-Ausdrucks
|
||||
# z.B. fuer Quantifizierung ?, +, *, {}
|
||||
# PLUS als Nebeneffekt werden Variablen erzeugt
|
||||
# ^ Anfang der Zeile
|
||||
# $ Ende der Zeile
|
||||
# .* Beliebig viele beliebige Zeichen (so viel wie geht)
|
||||
# .*? Beliebig viele beliebige Zeichen, non-greedy
|
||||
# [:space:] 1 Zeichen aus der Gruppe Spaces
|
||||
# \s 1 Whitespace (Space, Tab)
|
||||
regex = r'.*inet\s(([0-9]{1,3}\.){3}[0-9]{1,3})'
|
||||
addresses = []
|
||||
|
||||
for line in lines:
|
||||
match = re.match(regex, line)
|
||||
if match:
|
||||
#print(line)
|
||||
#print("Gesamte IP:", match.group(1))
|
||||
#print("3. Oktett :", match.group(2))
|
||||
#print("-" * 20)
|
||||
addresses.append(match.group(1))
|
||||
# Mehrfachzuweisung aller gefundener Gruppen
|
||||
# ip, dummy = match.groups()
|
||||
|
||||
return addresses
|
||||
|
||||
|
||||
def main():
|
||||
lines = read_from_command("ip address show")
|
||||
local_ips = extract_ip(lines)
|
||||
print("Aktuelle Adressen:", local_ips)
|
||||
|
||||
|
||||
hide_exception(main)
|
||||
Reference in New Issue
Block a user