使用PHP更改服务器的ip地址
问题描述:
我需要能够使用PHP更改服务器的IP地址。我正在尝试使用ifconfig eth0 down
作为www-data
用户,以确保它能正常工作。到目前为止,我已经摆脱了/ var/run/network/ifstate文件的权限问题,但是现在我得到了一个权限被拒绝的行,其内容为SIOCSIFFLAGS: Permission denied
。有没有解决的办法?如果不是,您如何更改网页中服务器的IP地址?使用PHP更改服务器的ip地址
PHP代码:
//if the ip has changed, bring down the network interface and bring it up with the new IP
if($ipConf != $ip) {
$ifdownSuccess = exec("ifconfig eth0 down", $downOutput, $downRetvar);
$ifupSuccess = exec("ifconfig eth0 up ".$ip, $upOutput, $upRetvar);
//TODO: check for ifupSucess and revert to old ip if the command failed
var_dump($downOutput);
var_dump($downRetvar);
var_dump($ifdownSuccess);
var_dump($upOutput);
var_dump($upRetvar);
var_dump($ifupSuccess);
}
回报:
array(0) { } int(127) string(0) "" array(0) { } int(127) string(0) ""
是有解决权限问题的方式或其他工具,我可以用它来做到这一点?
答
我想通了。答案是将www-data
用户(或者您的服务器用户的任何名称)添加到管理组usermod -a -G admin www-data
。如果您查看/etc/sudoers
,您会注意到该组中的任何人都可以使用sudo -n <command>
在没有密码提示的情况下执行sudo
命令。做了一个快速的代码更改:
//if the ip has changed, bring down the network interface and bring it up with the new IP
if($ipConf != $ip) {
$ifdownSuccess = exec("sudo -n ifconfig eth0 down", $downOutput, $downRetvar);
$ifupSuccess = exec("sudo -n ifconfig eth0 up ".$ip, $upOutput, $upRetvar);
//TODO: check for ifupSucess and revert to old ip if the command failed
var_dump($downOutput);
var_dump($downRetvar);
var_dump($ifdownSuccess);
var_dump($upOutput);
var_dump($upRetvar);
var_dump($ifupSuccess);
}
和我现在在生意。能够通过SSH连接新的IP地址,并通过新的IP查看网页。
答
我也有类似的问题,并正在考虑以下解决方案:
1)PHP页面的IP,子网掩码读取和网关,检查正确的格式,以及是否IP是可行的和写入到文本文件
2)写在任何一个cronjob,寻找该文件,如果它的存在,它在内容读取,分析它,并使得变更
这应该是足够安全的。
你不能使用sudo,只是让ifup/ifdown?这可以解决所有权限问题。 –
我认为只有root可以降低网络接口......但我可能是错的。 – NullUserException
但是我如何从php exec()调用中使用'sudo'?它需要在以下行上输入密码... – moonlightcheese