震惊!php还能这么玩!如何与可交互的程序进行交互

震惊!php还能这么玩!如何与可交互的程序进行交互

今天有幸看到一篇 shell中交互输入自动化 的文章,对于SDTIN的理解好像是又加深了一层

然后尝试用PHP来实现,果然是可以的,简直棒棒的。

祭出代码:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
<?php
/**
 * 与shell程序使用管道进行交互
 */

//定义要开启的管道
$descriptorspec = array(
   0 => array("pipe", "r"),  // 标准输入,子进程从此管道中读取数据
   1 => array("pipe", "w"),  // 标准输出,子进程向此管道中写入数据
   2 => array("file", "./error-output.txt", "a") // 标准错误,写入到一个文件
);

//读入要生成的文件名
if (!isset($argv[1])) {exit('请输入秘钥文件名!');}

$key_name = $argv[1];

//参数
$params =<<<PARAM
CN
Beijing
beijing
Rea .Ltd
technology section
reatang.com
admin@reatang.com

PARAM;

//打开进程
$process = proc_open("openssl req -new -newkey rsa:2048 -nodes -keyout {$key_name}.key -out {$key_name}.csr", $descriptorspec, $pipes, __DIR__);

if (is_resource($process)) {

    //与进程进行交互
    fwrite($pipes[0], $params);
    fclose($pipes[0]);

    //交互完成
    echo stream_get_contents($pipes[1]);
    fclose($pipes[1]);

    $return_value = proc_close($process);

    echo "command returned $return_value\n";
}

这样就自动完成了和命令的交互!OMG简直赞!还是我的基础功夫不扎实呀,之前学习给网站加证书的时候就在想如何能自动生成CSR文件,现在OK了!!

blob.png

Licensed under CC BY-NC-SA 4.0