如何使用SSH在另一台服务器上的PHP中运行CLI命令? [英] How to run CLI commands in PHP on another server using SSH?
问题描述
我正在尝试在PHP中但在另一台服务器上运行CLI命令。为了在另一台服务器上运行该命令,我使用了Linux ssh
命令。为了在PHP中运行CLI命令,我使用 exec()
。
I am trying to run CLI commands in PHP but on a different server. In order to run the command on the other server I am using the linux ssh
command. In order to run the CLI command in PHP I am using exec()
.
这可行... / p>
This works...
$output = exec('cut -d: -f1 /etc/passwd'); //works!
这可以从一台服务器的命令行到另一台服务器...
This works from the command line of one server to another...
ssh my.otherserver.com "date"
但是,当我尝试在PHP中执行此操作时...
But, when I try to do this in PHP it does not work...
$output = exec('ssh my.otherserver.com "date"'); //does not work!
我想做的是可能的吗?我该怎么做呢?预先感谢。
Is what I am trying to do possible? How do I do this? Thanks in advance.
推荐答案
ssh2_connect或phpseclib
您可以使用ssh2_connect或phpseclib。在我的EC2实例上,我必须安装ssh2_connect软件包(例如yum install php56-pecl-ssh2-0.12-5.15.amzn1.x86_64),因为默认情况下该软件包不存在。注意:这也可以使用bash脚本来完成。
You can use ssh2_connect or phpseclib. On my EC2 instance I had to install the package for ssh2_connect (e.g. yum install php56-pecl-ssh2-0.12-5.15.amzn1.x86_64) as it wasn't there by default. Note: this could be done with a bash script as well.
<?php
//ssh2_connect:
$connection = ssh2_connect('localhost', 22);
ssh2_auth_password($connection, 'user', 'password');
$stream = ssh2_exec($connection, 'ls -l > /tmp/worked.txt');
//phpseclib:
include('Net/SSH2.php');
$ssh = new Net_SSH2('www.example.com');
$ssh->login('username', 'password') or die("Login failed");
echo $ssh->exec('command');
进一步阅读:
http://phpseclib.sourceforge.net/
< a href = http://php.net/manual/zh/function.ssh2-connect.php rel = nofollow noreferrer> http://php.net/manual/zh/function.ssh2-connect.php
这篇关于如何使用SSH在另一台服务器上的PHP中运行CLI命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!