从php执行shell脚本
我想在远程设备上执行一些命令。我正在使用公钥和私钥连接到远程设备 在我的服务器中,我只需键入:sshusername@distant_device命令,我得到结果。所以我想通过一个php页面来实现这一点 我尝试了不同的方法,但对我无效 1- 2-在服务器中执行shell脚本 script.sh:从php执行shell脚本,php,shell,ssh,Php,Shell,Ssh,我想在远程设备上执行一些命令。我正在使用公钥和私钥连接到远程设备 在我的服务器中,我只需键入:sshusername@distant_device命令,我得到结果。所以我想通过一个php页面来实现这一点 我尝试了不同的方法,但对我无效 1- 2-在服务器中执行shell脚本 script.sh: #!/bin/bash output=$(ssh username@distant_device command) echo "$output" >> test.txt exit 0
#!/bin/bash
output=$(ssh username@distant_device command)
echo "$output" >> test.txt
exit 0
php代码:
passthru('./script.sh',$result);
echo $result ;
我得到了通过脚本发送的结果,但不是其中ssh命令的结果。当我直接执行脚本时,我得到了结果
3-
文本文件保持为空
我做错了什么?例如,您可以使用
shell\u exec()
$output = shell_exec('./deploy.sh');
echo "<pre>".$output."</pre>";
$output=shell_exec('./deploy.sh');
回显“$output.”;
Php有一个很好的文档
希望有帮助:)我找到了一个解决方案,在这里:
$host=“ip_地址”;
$port=22;
$conn=ssh2\u connect($host,$port);
$username=“username”;
$pub_key=“/path/to/key/.ssh/id_rsa.pub”;
$pri_key=“/path/to/key/.ssh/id_rsa”;
如果(ssh2_auth_pubkey_文件(
$conn,
$username,
$pub_key,
$pri_键)
{
echo“身份验证成功”;
$stdout_stream=ssh2_exec($conn,'ping ip_地址快速路由实例xxxxxxxx');
睡眠(1);
流设置阻塞($stdout\u stream,true);
$stream\u out=ssh2\u fetch\u stream($stdout\u stream,ssh2\u stream\u STDIO);
回声';
回显流获取内容($stream\u out);
回声';
}
其他的
{
echo“身份验证失败”;
}
我得到了同样的空结果:(
system ("ssh username@distant_device command > test.txt");
system ("ssh -i /home/nagios/.ssh/id_rsa -o 'StrictHostKeyChecking no' username@distant_device command' > test.txt");
$output = shell_exec('./deploy.sh');
echo "<pre>".$output."</pre>";
$host = "ip_address";
$port = 22;
$conn = ssh2_connect($host, $port);
$username = "username";
$pub_key = "/path/to/key/.ssh/id_rsa.pub";
$pri_key = "/path/to/key/.ssh/id_rsa";
if(ssh2_auth_pubkey_file(
$conn,
$username,
$pub_key,
$pri_key))
{
echo "Authentication succeeded";
$stdout_stream = ssh2_exec($conn, 'ping ip_address rapid routing-instance XXXXXXXXX');
sleep(1);
stream_set_blocking($stdout_stream, true);
$stream_out = ssh2_fetch_stream($stdout_stream, SSH2_STREAM_STDIO);
echo '<pre>';
echo stream_get_contents($stream_out);
echo '</pre>';
}
else
{
echo "Authentication failed ";
}