我有一个 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');
并且正在运行,所以这似乎是 linux 生成的文件或输出与 php 中的字符串之间的一个问题,但我该如何解决这个问题?
最佳答案
我解决了这个问题,因为它是一些特殊字符,最后我有代码:
$txt= shell_exec('./routeCk.sh ' . $ipCk . ' 22 commandeCk | dos2unix ');
这会将所有输出置于 unix 类型,但不是逻辑,与 linux 一起工作,输出带有 dos 字符
关于php - 读取文件/调用脚本在 preg_match_all 中的结果与代码中的文本不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27399691/