<?php
$conn = ssh2_connect('1.1.1.1', 22);
if (!$conn) {
die("conn fail\n");
}
if (ssh2_auth_password($conn, 'root', 'password')) {
echo "auth sus\n";
} else {
die("auth fail\n");
}
$stream = ssh2_exec($conn, "df --output=avail /|tail -n 1");
stream_set_blocking($stream, true);
$res = trim(stream_get_contents($stream));
var_dump($res);
php使用ssh交互式执行命令:
<?php
$host = '192.168.1.1';
$port = 2222;
$pass = 'xxxx';
if (!($conn = ssh2_connect($host, $port, array('hostkey'=>'ssh-rsa')))) {
die("conn fail\n");
}
//注意路径不要使用~/.ssh/id_rsa.pub,会遇到段错误和其它莫名其妙的问题
if (ssh2_auth_pubkey_file($conn, 'root', '/root/.ssh/id_rsa.pub', '/root/.ssh/id_rsa')) {
echo "auth sus\n";
} else {
die("auth fail\n");
}
function expect($stream, $match) {
$time = time();
$res = '';
while(!feof($stream)){
//if (($buffer = fgets($stream, 4096)) !== false) {
if (($buffer = fread($stream, 4096)) !== false) {
$res .= $buffer;
}
if (stristr($res, $match)) {
return 'sus';
}
$now = time();
if (($now - $time) >= 10) {
return 'timeout';
}
usleep(100);
}
return 'disconnect';
}
$shell=ssh2_shell($conn, 'xterm');
fwrite($shell, "/usr/bin/cryptroot-unlock\n");
$res = expect($shell, 'Please unlock disk');
if ($res == 'sus') {
fwrite($shell, "{$pass}\n");
$res = expect($shell, 'set up successfully');
if ($res == 'sus') {
}
var_dump($res);
}
php也可安装expect扩展调用ssh命令交互式执行命令:
apt install php-dev tcl-dev tcl-expect-dev
wget https://pecl.php.net/get/expect-0.4.0.tgz
tar zxvf expect-0.4.0.tgz
cd expect-0.4.0/
phpize
./configure
make && make install
echo 'extension=expect.so' > /etc/php/7.4/cli/conf.d/20-expect.ini
php -m|grep expect
make时如果出现错误php_expect.h:34:10: fatal error: expect_tcl.h: 没有那个文件或目录:
sed -i 's/^INCLUDES =/INCLUDES = -I\/usr\/include\/tcl8.6/' Makefile
php使用expect连接ssh执行命令:
<?php
ini_set("expect.timeout", 2);
ini_set("expect.loguser", "off");
$stream = expect_popen("ssh -o StrictHostKeyChecking=no -p 22 root@www.haiyun.me");
$cases = array(
array("password:", "password"),
array("Last login", "shell"),
array("yes/no)?", "yes/no")
);
while (true) {
switch (expect_expectl($stream, $cases)) {
case "password":
fwrite($stream, "password\n");
break;
case "yes/no":
fwrite($stream, "yes\n");
break;
case "shell":
fwrite($stream, "uptime\n");
break;
case EXP_TIMEOUT:
case EXP_EOF:
break 2;
default:
die("Error has occurred!");
}
}
fclose ($stream);
标签:php, ssh, expect, php远程ssh执行命令