我有一个PHP脚本,必须在一个结果shell脚本中搜索信息,这个shell脚本建立一个连接ssh,获取路由表并将其保存在一个.txt文件中,但是如果我尝试读取文件或直接从脚本中获取信息并使用preg_match_all进行搜索, 结果是空的,但我把结果直接放在我的文件 PHP 中,代码工作正常,所以我对这个问题迷失了方向,我的 PHP 代码是:
$resultsCK = array();
// ([0]) [1] [2] [3] [4] [5] [6] [7] ([8])
$searchTextG = "/(S|R|B|O|A|K|H|P|U|i) +(IA|E|N|) +([0-9.]+)'/([0-9]+) +via +([0-9.]+), +([a-zA-Z0-9.]+|), +cost +(?:[0-9]+:|)([0-9]+), +age +[0-9]+ +'n((?: +via +[0-9.]+, +(?:[a-zA-Z0-9.]+|) +'n)*)/";
$searchTextC = "/(C) +([0-9.]+)'/([0-9]+) +is directly connected, +([a-zA-Z0-9.]+) +'n/";
foreach ($ciscoCk as $ipCk) {
shell_exec('./tmp/routeCk.sh ' . $ipCk . ' 22 commandeCk > /tmp/resultRouteCk.txt');
$txt= file_get_contents('/tmp/resultRouteCk.txt');
$matches = [];
preg_match_all($searchTextG, $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $id => $match) {
unset($matches[$id][0]);
if (isset($match[8])) {
preg_match_all($searchSubTextG, $match[8], $subpatternMatches, PREG_SET_ORDER);
unset($matches[$id][8]);
foreach ($subpatternMatches as $spmid => $spm) {
unset($subpatternMatches[$spmid][0]);
$matches[$id][8][] = $subpatternMatches[$spmid];
}
}
}
//g of general
$resultsCK[$ipCk]["g"] = $matches;
$matches = [];
preg_match_all($searchTextC, $txt, $matches, PREG_SET_ORDER);
foreach ($matches as $id => $match) {
unset($matches[$id][0]);
}
$resultsCK[$ipCk]["c"] = $matches;
}
var_dump($resultsCK);
所以我已经尝试过了:
shell_exec('./tmp/routeCk.sh ' . $ipCk . ' 22 commandeCk > /tmp/resultRouteCk.txt');
$txt= file_get_contents('/tmp/resultRouteCk.txt');
这要:
$txt=('./tmp/routeCk.sh ' . $ipCk . ' 22 commandeCk');
并且不起作用,但是如果我把
$txt="
Codes: C - Connected, S - Static, R - RIP, B - BGP,
O - OSPF IntraArea (IA - InterArea, E - External, N - NSSA)
A - Aggregate, K - Kernel Remnant, H - Hidden, P - Suppressed,
U - Unreachable, i - Inactive
O E 0.0.0.0/0 via 10.140, bond1.30, cost 1:10, age 5
via 10.141, bond1.31
via 10.142, bond1.32
O E 10.112/23 via 10.140, bond1.30, cost 46:1, age 2511
O E 10.112/23 via 10.140, bond1.30, cost 46:1, age 2511
O IA 10.138/29 via 10.140, bond1.30, cost 46, age 1029440
C 10.141/29 is directly connected, bond2.35
C 10.141/29 is directly connected, bond2.35
";
脚本将起作用,并且这是文件中的相同信息,那么我该如何解决此问题? 可能是一些字符集问题?
写这篇文章,我测试更改 resultRouteCk 中的一行.txt并使用 $txt=('./tmp/routeCk.sh ' . $ipCk . ' 22 commandeCk');
测试 PHP 并且正在工作,所以这似乎是 linux 制作的文件或输出与 php 中的字符串之间的一个问题,但我如何解决这个问题?
我解决了这个问题,因为它是一些特殊字符,最后我有代码:
$txt= shell_exec('./routeCk.sh ' . $ipCk . ' 22 commandeCk | dos2unix ');
这将把所有的输出都放在 unix 类型中,但不是逻辑,使用 linux,具有带有 dos 字符的 ouptut