美文网首页
使用PHP获取服务器MAC物理网卡地址

使用PHP获取服务器MAC物理网卡地址

作者: 迅犀数科 | 来源:发表于2021-09-26 17:46 被阅读0次

    有个小需求是需要使用PHP来获取到服务器MAC物理网卡地址,于是通过百度获取了一段网上通用的获取方法:

    ```python

    //获取用户电脑MAC地址并生成唯一机器识别码

    class GetMacAddr

    {

        var $result  = array();

        var $macAddrs = array(); //所有mac地址

        var $macAddr;            //第一个mac地址

        function __construct($OS){

            $this->GetMac($OS);

        }

        function GetMac($OS){

            switch ( strtolower($OS) ){

                case "unix": break;

                case "solaris": break;

                case "aix": break;

                case "linux":

                    $this->getLinux();

    break;

                default:

                    $this->getWindows();

    break;

            }

            $tem = array();

            foreach($this->result as $val){

                if(preg_match("/[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f][:-]"."[0-9a-f][0-9a-f]/i",$val,$tem) ){

                    $this->macAddr = $tem[0];//多个网卡时,会返回第一个网卡的mac地址,一般够用。

                    break;

                    //$this->macAddrs[] = $temp_array[0];//返回所有的mac地址

                }

    }

            unset($temp_array);

            return $this->macAddr;

        }

        //Linux系统

        function getLinux(){

            @exec("/usr/sbin/ifconfig -a", $this->result);

            //var_dump($this->result);

            return $this->result;

        }

        //Windows系统

        function getWindows(){

            @exec("ipconfig /all", $this->result);

            if ( $this->result ) {

                return $this->result;

            } else {

                $ipconfig = $_SERVER["WINDIR"]."\system32\ipconfig.exe";

                if(is_file($ipconfig)) {

                    @exec($ipconfig." /all", $this->result);

                } else {

                    @exec($_SERVER["WINDIR"]."\system\ipconfig.exe /all", $this->result);

                    return $this->result;

                }

    }

    }

    }

    ```

    这个代码在window主机下没问题,但是在linux主机上发现获取到的mac地址为空,经过一番排查发下,主要由于一下原因引起:

    用which找到该Linux命令的绝对路径,使用绝对路径执行就可以了

    举例:

    ```python

    exec("ifconfig -a",$output);

    -------------

    #which ifconfig  或则whereis ifconfig

    exec("/sbin/ifconfig -a",$output);

    ```

    所以,把上面的Linux系统获取mac的方法调整成完整的路径(需要自己去服务器上使用which查询完整路径)就好了,

    ```python

    //Linux系统

    function getLinux(){

        @exec("/usr/sbin/ifconfig -a", $this->result);

        return $this->result;

    }

    ```

    相关文章

      网友评论

          本文标题:使用PHP获取服务器MAC物理网卡地址

          本文链接:https://www.haomeiwen.com/subject/oqzqnltx.html