【发布时间】:2023-04-08 13:56:01
【问题描述】:
我尝试发布:
sudo apt-get update
和
sudo apt-get install openjdk-7-jre joe wget
在远程机器上通过 php,
我一直在环顾四周,尝试了两种方法:
第一:
session_start();
$command = "ssh -o 'StrictHostKeyChecking no' -i /var/www/.ssh/my-keypair555.pem ubuntu@{$_SESSION['host']} \"sudo apt-get update\"";
echo $command."<br/>";
echo exec($command, $output);
print_r($output);
$command = "ssh -o 'StrictHostKeyChecking no' -i /var/www/.ssh/my-keypair555.pem ubuntu@{$_SESSION['host']} \"sudo apt-get install -y openjdk-7-jre joe wget\"";
echo $command."<br/>";
echo exec($command, $output);
print_r($output);
这段代码似乎根本没有被执行, (命令被打印但输出数组似乎是空的。)
其次: 改编自http://php.net/manual/en/function.ssh2-exec.php
session_start();
$connection = ssh2_connect($_SESSION['host'], 22, array('hostkey'=>'ssh-rsa'));
if (ssh2_auth_pubkey_file(
$connection,
'ubuntu',
'/var/www/.ssh/id_rsa.pub',
'/var/www/.ssh/id_rsa')
) {
$shell = ssh2_shell($connection,"bash");
$cmd = "echo '[start]';sudo apt-get update;sudo apt-get install -y openjdk-7-jre joe wget;echo '[end]'";
$output = user_exec($shell,$cmd);
fclose($shell);
echo $output."<br/>";
} else {
die('Public Key Authentication Failed');
}
function user_exec($shell,$cmd) {
fwrite($shell,$cmd . "\n");
$output = "";
$start = false;
$start_time = time();
$max_time = 900; //time in seconds
while(((time()-$start_time) < $max_time)) {
$line = fgets($shell);
//echo $line;
if(!strstr($line,$cmd)) {
if(preg_match('/\[start\]/',$line)) {
$start = true;
echo "start";
}elseif(preg_match('/\[end\]/',$line)) {
return $output;
}elseif($start){
$output[] = $line;
echo $line."<br/>";
}
}
}
}
如果我使用此代码命令:
echo '[start]';sudo apt-get update;sudo apt-get install -y openjdk-7-jre joe wget;echo '[end]'
如果我登录机器并发出问题就会显示
history
但似乎没有被执行,因为如果我发出
java
我收到需要安装它的消息。
如果我发出
!1
apt-get update 和 apt-get install 确实可以正确执行。
如果我在浏览器中运行 php 文件,我会得到以下输出:
欢迎使用 Ubuntu 14.04.1 LTS(GNU/Linux 3.13.0-36-generic x86_64)* 文档:https://help.ubuntu.com/ 系统信息截至 2015 年 2 月 8 日星期日 17:20:45 UTC 系统负载:0.69 进程:104 / 的使用:7.74GB 的 9.8% 登录用户:0 内存使用:1% eth0 的 IP 地址:10.74.190.178 交换使用:0% 绘制此数据并在以下位置管理此系统:https://landscape.canonical.com/ 使用 Ubuntu Advantage 获得云支持云访客:http://www.ubuntu.com/business/services/cloud 0 个包可以更新。 0 更新是安全更新。上次登录:2015 年 2 月 8 日星期日 17:20:50 来自 ec2-54-77-56-210.eu-west-1.compute.amazonaws.com echo '[start]';sudo apt-get update;sudo apt- get install -y openjdk-7-jre joe wget;echo '[end]' ubuntu@ip-10-74-190-178:~$ echo '[start]';sudo apt-get update;sudo apt-get in
- 很多空行,不时出现双重消息,例如 阿拉尔 要么 l -l -
-> 请注意,该命令在“安装”处被截断
这将解释为什么该命令没有被执行。
谁能帮我解决这个问题,我已经搜索了将近两个星期,似乎没有太大进展......
谢谢,
砂光机
【问题讨论】:
标签: php bash ubuntu ssh amazon-ec2