我想编辑/创建或删除安装在Raspberry Pi中的dhcpd.conf文件的一部分区域。
我想编辑/etc/dhcpcd.conf中的文件,如果它包含静态ip config块,我将更新此块,否则,我想创建此块,并且在某些情况下也希望删除该块而不会损坏文件的任何其他部分。因此,我必须在配置文件中编写一个执行该操作的函数。我看到了ConfigParser软件包,但是我不确定使用它。我该如何解决这个问题?
我使用这种解决方案,但它不可靠且无法正常工作。也许使用ConfigParse比这更干净的解决方案。
interface eth0
static ip_address=192.168.0.4/24
static routers=192.168.0.1
static domain_name_servers=192.168.0.1
@staticmethod
def change_static_ip(ip_address, routers, dns):
conf_file = '/etc/dhcpcd.conf'
try:
vars = ['interface', 'static ip_address', 'static routers', 'static domain_name_servers']
new_values = ['eth0', ip_address, routers, dns]
changes = dict(zip(vars,new_values))
RE = '(('+'|'.join(changes.keys())+')\s*=)[^\r\n]*?(\r?\n|\r)'
pat = re.compile(RE)
def jojo(mat,dic = changes):
return dic[mat.group(2)].join(mat.group(1,3))
with open(conf_file,'rb') as f:
content = f.read().decode('utf-8')
with open(conf_file,'wb') as f:
f.write(pat.sub(jojo,content))
except Exception as ex:
logging.exception("IP changing error: %s", ex)
finally:
pass
我也在寻找相同的解决方案时发现了您的问题,所以我决定自己尝试一下。
基于您的示例,我将展示我所做的类似工作:
@staticmethod
def change_static_ip(ip_address, routers, dns):
conf_file = '/etc/dhcpcd.conf'
try:
# Sanitize/validate params above
with open(conf_file, 'r') as file:
data = file.readlines()
# Find if config exists
ethFound = next((x for x in data if 'interface eth0' in x), None)
if ethFound:
ethIndex = data.index(ethFound)
if ethFound.startswith('#'):
ethFound.replace('#', '') # commented out by default, make active
# If config is found, use index to edit the lines you need ( the next 3)
if ethIndex:
data[ethIndex+1] = f'static ip_address={ip_address}/24'
data[ethIndex+2] = f'static routers={routers}'
data[ethIndex+3] = f'static domain_name_servers={dns}'
with open(conf_file, 'w') as file:
file.writelines( data )
except Exception as ex:
logging.exception("IP changing error: %s", ex)
finally:
pass
如果需要传递一个参数来删除eth0的静态配置,请像这样先向其添加'#':
'#interface eth0'