PeclのExpectがかなり使い易い

Bashとかから普通に使うより遥かに楽。
opensslでパスフレーズなしの秘密鍵と公開鍵を作ってみた。
面倒な対話がなくなってこりゃ便利。
 
$case[] = array(正規表現, 返す文字列);
 

<?php
$domain = 'example.com';
$phrase = 'hoge';

makePrivateKey($domain, $phrase);
makePublicKey($domain, $phrase);
delPassPhrase($domain, $phrase);

function makePrivateKey($domain, $phrase) {
	$f = expect_popen("/usr/bin/openssl genrsa -des3 1024 > /tmp/https_{$domain}.key");
	$case = array(
		array('phrase:', 'phrase')
	);
	while (true) {
		switch (expect_expectl($f, $case)) {
		case 'phrase':
			fwrite($f, $phrase."\n");
			break;
		case EXP_TIMEOUT:
			return "timeout";
			break;
		case EXP_EOF:
			return "eof";
			break;
		default:
			return "error";
			break;
		}
	}
}

function makePublicKey($domain, $phrase, $gb='JP', $berkshire='Tokyo', $newbury='Shinjuku') {
	$f = expect_popen("/usr/bin/openssl req -utf8 -new -key /tmp/https_{$domain}.key -x509 -days 3650 -out /tmp/https_{$domain}.crt -set_serial 0");
	$case = array(
		array('.key:', 'phrase'),
		array('\[GB\]:', 'gb'),
		array('\[Berkshire\]:', 'berkshire'),
		array('\[Newbury\]:', 'newbury'),
		array('\[My Company Ltd\]:', 'company'),
		array('section) \[\]:', 'unit'),
		array('hostname) \[\]:', 'hostname'),
		array('Address \[\]:', 'email')
	);
	while (true) {
		switch(expect_expectl($f, $case)){
		case 'phrase':
			fwrite($f, $phrase."\n");
			break;
		case 'gb':
			fwrite($f, $gb."\n");
			break;
		case 'berkshire':
			fwrite($f, $berkshire."\n");
			break;
		case 'newbury':
			fwrite($f, $newbury."\n");
			break;
		case 'company':
		case 'unit':
		case 'hostname':
			fwrite($f, $domain."\n");
			break;
		case 'email':
			fwrite($f, 'root@'.$domain."\n");
			break;
		case EXP_TIMEOUT:
			return "timeout";
			break;
		case EXP_EOF:
			return "eof";
			break;
		default:
			return "error";
			break;
		}
	}
}

function delPassPhrase($domain, $phrase) {
	$f = expect_popen("/usr/bin/openssl rsa -in /tmp/https_{$domain}.key -out /tmp/https_{$domain}.key");
	$case = array(
		array('.key', 'phrase')
	);
	while (true) {
		switch (expect_expectl($f, $case)) {
		case 'phrase':
			fwrite($f, $phrase."\n");
			break;
		case EXP_TIMEOUT:
			return "timeout";
			break;
		case EXP_EOF:
			return "eof";
			break;
		default:
			return "error";
			break;
		}
	}
}

 
PHP: Expect の使用例 - Manual
http://www.php.net/manual/ja/expect.examples-usage.php