问题描述
我有一个名为 named.conf
的文件,它是 BIND 的配置文件。它有用花括号括起来的条目。我想使用 PHP 在内部和外部视图中编辑和输入一个新区域条目。我怎样才能做到这一点。有图书馆吗
可用于编辑此类配置文件?
view "internal"
{
match-clients { localnets; };
match-destinations { localnets; };
recursion yes;
include "/etc/named.root.hints";
zone "my.internal.zone" {
type master;
file "my.internal.zone.db";
};
};
view "external"
{
match-clients { !localnets; !localhost; };
match-destinations { !localnets; !localhost; };
recursion no;
include "/etc/named.root.hints";
zone "my.external.zone" {
type master;
file "my.external.zone.db";
};
};
解决方法
您可以使用file_get_content(),更新文件内容,然后使用file_put_content()推送新数据。
我们需要的是一些需要插入新行的注释:
view "internal"
{
match-clients { localnets; };
match-destinations { localnets; };
recursion yes;
include "/etc/named.root.hints";
#INTERNAL
zone "my.internal.zone" {
type master;
file "my.internal.zone.db";
};
};
view "external"
{
match-clients { !localnets; !localhost; };
match-destinations { !localnets; !localhost; };
recursion no;
include "/etc/named.root.hints";
#EXTERNAL
zone "my.external.zone" {
type master;
file "my.external.zone.db";
};
};
这样你就可以用 PHP 捕捉你的评论并在之后添加内容:
$confText = file_get_contents('your_file_path') ;
$newExternalZone = PHP_EOL.
'zone "my.new.external.zone" {
type master;
file "my.new.external.zone.db";
};'.PHP_EOL ;
preg_replace("/(#EXTERNAL)/","$1".$newExternalZone,$confText) ;
file_put_contents('your_file_path',$confText) ;
这里的代码很简单,抓住 #External 并将 $newExternalZone 放在后面! 您可以更新和使用来自 POST、GET 或其他用于 newExternalZone 的数据。
,我能够使用下面的代码来做到这一点。该代码使用 PHP CLI 接受参数并使用这些值创建一个新文件。
$file = file('named.conf');
$arg = getopt("",array('zone:','type:','file:'));
$internal_end = 0;
$external_end = 0;
$flag = false;
$count = 0;
foreach ($file as $index => $line) {
if (preg_match('/view\s*"internal"\s*{/i',$line) !== 1 && !$flag) {
continue;
}
$flag = true;
$ob = substr_count($line,'{');
$count += $ob;
$cb = substr_count($line,'}');
$count -= $cb;
if ($count == 0) {
$internal_end = $index;
break;
}
}
array_splice($file,$internal_end,array(
"\n","zone \"".$arg['zone']."\" {\n","\ttype ".$arg['type'].";\n","\tfile \"".$arg['file']."\";\n","};\n","\n"
));
$flag = false;
$count = 0;
foreach ($file as $index => $line) {
if (preg_match('/view\s*"external"\s*{/i','}');
$count -= $cb;
if ($count == 0) {
$external_end = $index;
break;
}
}
array_splice($file,$external_end,"\n"
));
file_put_contents('named_new.conf',implode('',$file));
执行代码调用php script.php --zone=my.new.external.zone --type=master --file=my.new.external.zone.db