#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Class for read or modify /etc/network/interfaces.d/XXX files
It not preparated for vlans
Last versión:
http://lwp-l.com/s5387
checkInterfacesSource() - Check if interfaces file has a source....
readFiles() - Read al files in /etc/network/interfaces.d/ folder and fill the dictionary
getValue() - Get value of the interface
setValue() - Update or add value
createIface() - create an iface .... (iface eth0 inet static)
getValueIface() - Get value of the iface
setValueIface() - Update or add a value in iface
removeIFace() - Remove iface
removeInterface() - Remove file of the interface
save() - Save any changes to the files
config file is similar to:
auto eth0 getValue(), setValue()
allow-hotplug eth0 getValue(), setValue()
iface eth0 inet static createIface(), getValueIface()
address 192.168.0.102 getValueIface(), setValueIface()
netmask 255.255.255.0 getValueIface(), setValueIface()
network 192.168.0.0 getValueIface(), setValueIface()
broadcast 192.168.0.255 getValueIface(), setValueIface()
gateway 192.168.0.2 getValueIface(), setValueIface()
"""
import os, sys
from subprocess import Popen, PIPE
import glob
import re
__ver__="0.1"
class Interfaces():
folder="/etc/network/interfaces.d/"
""" list that contain the files with its content
files
{fileName1:[[value1, value2], [iface, value1]]},
{fileName2:[[values], [values iface]]}
"""
files={}
def __init__(self,folder=""):
if folder:
self.folder=folder
def checkInterfacesSource(self, file="/etc/network/interfaces", find="source /etc/network/interfaces.d/*"):
"""
Check if exist "source /etc/network/interfaces.d/*" in /etc/network/interfaces
Return:
boolean
"""
if not os.path.exists(file):
return False
with open(file, "r") as f:
for line in f:
if line.strip()==find:
return True
return False
def readFiles(self):
"""
This function read files in /etc/network/interfaces.d/* an set data into var
Return
boolean - False if not possible read the files
"""
self.files={}
inIface=False
for fileName in os.listdir(self.folder):
self.files[fileName]=[[],[]]
with open(os.path.join(self.folder,fileName),"r") as f:
for line in f:
line=line.strip()
if line and line[0]!="#":
if len(line)>=6 and line[:6]=="iface ":
inIface=True
if inIface:
self.files[fileName][1].append(line)
else:
self.files[fileName][0].append(line)
return True
def getValue(self, interface, key):
"""
Function that return a line for a value of the interface
Find the text that start line to len the value is same
Parameteres:
interface string
key string
Return:
string
"""
self._checkInterfaceInFiles(interface)
for line in self.files[interface][0]:
if len(line)>=len(key) and line[0:len(key)]==key:
return line
return ""
def setValue(self, interface, key, value):
"""
Function to update value if exist or add new value if not exists
Parameters:
interface string
key string
value string
return:
integer - [1 updated, 2 insert]
"""
self._checkInterfaceInFiles(interface)
for i in range(len(self.files[interface][0])):
line=self.files[interface][0][i]
if len(line)>=len(key) and line[0:len(key)]==key:
self.files[interface][0][i]=key+" "+value.strip()
return 1
self.files[interface][0].append(key+" "+value)
return 2
def createIface(self, interface, addressFamily, method):
"""
Create the iface for a interface
Parameters:
interface string
addressFamily string - inet, inet6, ipx
method string - static, dhcp
Return:
boolean - true if is created | false if exists
"""
self._checkInterfaceInFiles(interface)
if len(self.files[interface][1])>0:
return False
self.files[interface][1].append("iface {} {} {}".format(interface, addressFamily, method))
return True
def removeIFace(self, interface):
"""
function that remove the iface in a interface
Parameters:
interface string
Return:
boolean - [True removed|False not exists interface]
"""
if self.files[interface]:
self.files[interface][1]=[]
return True
return False
def getValueIface(self, interface, key):
"""
Function that return a line for a iface in interface
Find the text that start line to len the value is same
Parameteres:
interface string
key string
Return:
string
"""
self._checkInterfaceInFiles(interface)
for line in self.files[interface][1]:
if len(line)>=len(key) and line[0:len(key)]==key:
return line
return ""
def setValueIface(self, interface, key, value):
"""
Function to update value if exist or add new value if not exists
Parameters:
interface string
key string
value string
return:
integer - [1 updated|2 insert|-1 not exists iface in this interface. Execute first self.createIface()]
"""
self._checkInterfaceInFiles(interface)
if len(self.files[interface][1])==0:
return -1
for i in range(len(self.files[interface][1])):
line=self.files[interface][1][i]
if len(line)>=len(key) and line[0:len(key)]==key:
self.files[interface][1][i]=key+" "+value.strip()
return 1
self.files[interface][1].append(key+" "+value)
return 2
def removeInterface(self, interface):
"""
Function to remove the interface file and interface in self.files
Parameters:
interface string
Return:
boolean - False not remove the file
"""
if not os.access(os.path.join(self.folder, interface), os.W_OK):
return False
try:
os.remove(os.path.join(self.folder, interface))
del self.files[interface]
return True
except:
return False
def _checkInterfaceInFiles(self, interface):
"""
Check if interface exists in dictionary self.files. if it does not exist it creates it
Parameters:
interface string
"""
if not interface in self.files:
self.files[interface]=[[], []]
return False
return True
def save(self):
"""
This function save the files with the changes
Return:
int - number of files saved | -1 not writable file
"""
if not os.access(self.folder, os.W_OK):
return -1
filesSaved=0
for file in self.files:
if self.files[file][0]==[] and self.files[file][1]==[]:
continue
with open(os.path.join(self.folder,file), "w") as f:
filesSaved+=1
f.write("# file created from class interfaces.py\n")
f.write("# http://lwp-l.com/s5387\n\n")
for line in self.files[file][0]:
f.write(line+"\n")
for line in self.files[file][1]:
f.write(line+"\n")
return filesSaved
Comentarios sobre la versión: 0.1 (1)