dongzhuo0895 2011-11-25 16:35
浏览 324
已采纳

使用PHP更改服务器的IP地址

i need to be able to change the IP address of a server using PHP. i'm trying to use ifconfig eth0 down as the www-data user to make sure it will work. so far, i've gotten rid of a permissions issue on /var/run/network/ifstate file, but now i get a permission denied line that reads SIOCSIFFLAGS: Permission denied. is there a way around this? if not, how do you change the IP address of a server in a web page?

php code:

//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);
}

returns:

array(0) { } int(127) string(0) "" array(0) { } int(127) string(0) ""

is there a way around this permissions issue or another tool i can use to do this?

  • 写回答

2条回答 默认 最新

  • dtrn74832 2011-11-25 17:24
    关注

    i figured this out. the answer was to add the www-data user (or whatever the name of your server user is) to the admin group with usermod -a -G admin www-data. if you take a look at /etc/sudoers, you'll notice that anyone in this group can perform sudo commands without a password prompt using sudo -n <command>. made a quick code change:

    //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);
    }
    

    and i'm now in business. was able to connect on the new IP address via SSH and view webpages via the new IP as well.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?