使用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) "" 

是有解决权限问题的方式或其他工具,我可以用它来做到这一点?

+0

你不能使用sudo,只是让ifup/ifdown?这可以解决所有权限问题。 –

+0

我认为只有root可以降低网络接口......但我可能是错的。 – NullUserException

+0

但是我如何从php exec()调用中使用'sudo'?它需要在以下行上输入密码... – moonlightcheese

我想通了。答案是将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查看网页。

+2

请注意,存在许多与www-data用户能够执行根级别相关的安全风险,尤其是在您将其配置为不需要密码的情况下。换句话说,如果您的应用程序以任何方式受到攻击,攻击者可以*地做任何他想做的事情。请考虑使用visudo来限制www-data访问的可执行文件,例如在本文中:http://*.com/questions/8202887/why-php-command-execservice-apache2-restart-doest-work- on-Ubuntu – nrobey

+1

只是为了加强,给sudo权限给http用户是一个非常糟糕的主意。 – jweyrich

我也有类似的问题,并正在考虑以下解决方案:

1)PHP页面的IP,子网掩码读取和网关,检查正确的格式,以及是否IP是可行的和写入到文本文件

2)写在任何一个cronjob,寻找该文件,如果它的存在,它在内容读取,分析它,并使得变更

这应该是足够安全的。