这是一个基本的工作示例。
<?php
$whois = 'whois.isoc.org.il'; // server to connect to for whois
$data = 'drew.co.il'; // query to send to whois server
$errFile = '/tmp/error-output.txt'; // where stderr gets written to
$command = "proxychains telnet $whois 43"; // command to run for making query
// variables to pass to proc_open
$cwd = '/tmp';
$env = null;
$descriptorspec = array(
0 => array("pipe", "r"), // stdin is a pipe that the child will read from
1 => array("pipe", "w"), // stdout is a pipe that the child will write to
2 => array("file", "/tmp/error-output.txt", "a") // stderr is a file to write to
);
// process output goes here
$output = '';
// store return value on failure
$return_value = null;
// open the process
$process = proc_open($command, $descriptorspec, $pipes, $cwd, $env);
if (is_resource($process)) {
echo "Opened process...\n";
$readBuf = '';
// infinite loop until process returns
for(;;) {
usleep(100000); // dont consume too many resources
// TODO: implement a timeout
$stat = proc_get_status($process); // get info on process
if ($stat['running']) { // still running
$read = fread($pipes[1], 4096);
if ($read) {
$readBuf .= $read;
}
// read output to determine if telnet connected successfully
if (strpos($readBuf, "Connected to $whois") !== false) {
// write our query to process and append newline to initiate
fwrite($pipes[0], $data . "\n");
// read the output of the process
$output = stream_get_contents($pipes[1]);
break;
}
} else {
// process finished before we could do anything
$output = stream_get_contents($pipes[1]); // get output of command
$return_value = $stat['exitcode']; // set exit code
break;
}
}
echo "Execution completed.\n";
if ($return_value != null) {
var_dump($return_value, file_get_contents($errFile));
} else {
var_dump($output);
}
// close pipes
fclose($pipes[1]);
fclose($pipes[0]);
// close process
proc_close($process);
} else {
echo 'Failed to open process.';
}
这应该从命令行运行,但并非必须如此。我试图很好地评论它。基本上一开始你就可以设置whois服务器和要查询的域。
该脚本使用进程打开 http://php.net/proc_open开一个proxychains
调用 telnet 的进程。它检查进程是否已成功打开,如果是,则检查其状态是否正在运行。在运行时,它将 telnet 的输出读取到缓冲区中,并查找字符串 telnet 输出以指示我们已连接。
一旦检测到 telnet 连接,它就会将数据写入进程,后跟换行符 (\n
),然后从 telnet 数据所在的管道中读取数据。一旦发生这种情况,它就会跳出循环并关闭进程和句柄。
您可以从指定的文件中查看 proxychains 的输出$errFile
。其中包含连接信息以及连接失败时的调试信息。
可能需要进行一些额外的错误检查或流程管理以使其更加健壮,但是如果将其放入函数中,您应该能够轻松调用它并检查返回值以查看查询是否成功。
希望这能为您提供一个良好的起点。
另请查看我的这个答案,了解另一个工作示例proc_open
,此示例实现了超时检查,因此如果命令在一定时间内未完成,您可以退出:在 Linux 上创建 PHP 在线评分系统:exec 行为、进程 ID 和 grep https://stackoverflow.com/questions/9356250/creating-a-php-online-grading-system-on-linux-exec-behavior-process-ids-and-g/9357331#9357331