PHP从复杂字符串中选择文本
我正在从运行ifconfig命令的linux设备中获取输出。我通过运行shell_exec命令来实现这一点。我找到了一个例子,但我似乎无法进一步研究它 这是我当前的代码PHP从复杂字符串中选择文本,php,linux,preg-match-all,shell-exec,ifconfig,Php,Linux,Preg Match All,Shell Exec,Ifconfig,我正在从运行ifconfig命令的linux设备中获取输出。我通过运行shell_exec命令来实现这一点。我找到了一个例子,但我似乎无法进一步研究它 这是我当前的代码 public function get_network_interfaces() { // Run the command. $cmd_exec = shell_exec("/sbin/ifconfig"); // Get the pattern. $pattern = '/inet addr
public function get_network_interfaces() {
// Run the command.
$cmd_exec = shell_exec("/sbin/ifconfig");
// Get the pattern.
$pattern = '/inet addr:([\d]{1,3}\.[\d]{1,3}\.[\d]{1,3}\.[\d]{1,3})/';
if (preg_match_all($pattern, $cmd_exec, $matches)) {
$interfaces = $matches[1];
return $interfaces;
}
}
这个(foreach'ing之后)的输出是简单的;192.168.1.1/127.0.0.1因为它有两个网络适配器,所以ifconfig的输出为
eth0 Link encap:Ethernet HWaddr 00:16:3e:38:b8:1c
inet addr:192.168.1.1 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: 2a02:2308::216:3eff:fe38:b81c/64 Scope:Global
inet6 addr: fe80::216:3eff:fe38:b81c/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
RX packets:10612623 errors:0 dropped:0 overruns:0 frame:0
TX packets:151855 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:1000
RX bytes:539434883 (514.4 MiB) TX bytes:37861938 (36.1 MiB)
Interrupt:30
lo Link encap:Local Loopback
inet addr:127.0.0.1 Mask:255.0.0.0
inet6 addr: ::1/128 Scope:Host
UP LOOPBACK RUNNING MTU:16436 Metric:1
RX packets:6662 errors:0 dropped:0 overruns:0 frame:0
TX packets:6662 errors:0 dropped:0 overruns:0 carrier:0
collisions:0 txqueuelen:0
RX bytes:768641 (750.6 KiB) TX bytes:768641 (750.6 KiB)
我试图得到的是接口的名称(eth0和lo),以及inet adds(它已经工作了),后面是RX字节和TX字节。
如果名字太难得到,那就这样吧。但是谁能解释一下如何获取RX字节和TX字节
谢谢。对于接口的名称,这应该可以:
$pattern = '/^(\w*)\s*Link encap.*$/';
对于RX和TX字节:
$pattern = '/RX packets:(\d*) /';
$pattern = '/TX packets:(\d*) /';
您应该进行测试,以确保您拥有每个接口的所有信息:
continue
)
另外,请注意您在系统中使用的语言,因为使用西班牙语您会得到“Paquetes RX:”。为了确保代码更加健壮,您应该尝试使用
shell\u exec
将环境变量LC\u MESSAGES
设置为en\u us.utf-8
。对于接口的名称,这应该可以:
$pattern = '/^(\w*)\s*Link encap.*$/';
对于RX和TX字节:
$pattern = '/RX packets:(\d*) /';
$pattern = '/TX packets:(\d*) /';
您应该进行测试,以确保您拥有每个接口的所有信息:
continue
)
另外,请注意您在系统中使用的语言,因为使用西班牙语您会得到“Paquetes RX:”。为了确保代码更加健壮,您应该尝试使用
shell_exec
将环境变量LC_MESSAGES
设置为en_us.utf-8
。您可以使用cat/proc/net/dev
以更容易解析的方式获取设备列表和rec/tr字节统计信息,如果您有接口,您可以使用ip addr show eth0 | grep inet
为ip本身获取一个易于解析的字符串。您可以使用cat/proc/net/dev
以更易于解析的方式获取设备列表和rec/tr字节统计信息,如果您有接口,您可以使用ip addr show eth0 | grep inet
为ip本身获取一个易于解析的字符串。可能重复的,谢谢。除了名字,这个不起作用。我自己尝试了一些方法,但似乎不起作用。谢谢,我会考虑改变一下。谢谢。除了名字,这个不起作用。我自己尝试了一些方法,但似乎不起作用。谢谢,我会考虑改变这个设置。