简体   繁体   English

如何使用PHP和远程ssh从文本文件中获取信息?

[英]How to get information from text file using PHP and remote ssh?

I've got this problem with very poor performance with PHP executing bash script with remote ssh and doing a grep on a log. 我遇到了这样的问题,即PHP用远程ssh执行bash脚本并在日志上执行grep时,性能非常差。 In web browser I receive output after 40 seconds. 在网络浏览器中,我在40秒后收到输出。 Executing bash script(ssh + grep on remote machine) directly over my local machine is taking 8 seconds. 直接在本地计算机上执行bash脚本(远程计算机上的ssh + grep)需要8秒钟。 I know I cannot bypass this so I came up with idea of : 我知道我不能绕过这个,所以我想到了:

Creating PHP script which will save to a text file on a local machine all "variables" I need. 创建PHP脚本,它将我需要的所有“变量”保存到本地计算机上的文本文件中。 Let's call it "parameters.txt". 我们称之为“ parameters.txt”。 Then other bash script "reader.sh" will read this "parameters.txt" file, do all of the magic of remote ssh and grep, then save output to "output.txt". 然后其他bash脚本“ reader.sh”将读取此“ parameters.txt”文件,执行远程ssh和grep的所有功能,然后将输出保存到“ output.txt”。 Background script will run every 2 seconds the reader.sh 后台脚本将每2秒运行一次reader.sh

Is it a good idea? 这是个好主意吗?

If you really need to use PHP over SSH, you could use something like http://phpseclib.sourceforge.net/ . 如果您确实需要通过SSH使用PHP,则可以使用诸如http://phpseclib.sourceforge.net/之类的东西。 They have a nice ssh implementation which I used for sometime for deploy applications and configure Linux servers (puppet replaced it). 他们有一个很好的ssh实施,我曾经用它来部署应用程序和配置Linux服务器(用人偶代替了它)。 Your code will be cleaner and easy to maintain. 您的代码将更加整洁且易于维护。

Another option is, if you are reading logs from Linux ( messages, apache, syslog, etc...) you have options with Rsyslog ( http://www.rsyslog.com/ ) to centralize it on a server and work on it locally. 另一个选择是,如果您正在从Linux读取日志(消息,apache,syslog等),则可以选择使用Rsyslog( http://www.rsyslog.com/ )将其集中在服务器上并对其进行处理本地。 This would be cheaper for your computers and easier to deploy. 这对于您的计算机而言更便宜,并且更易于部署。

Here is how you do it fast. 这是您快速执行的方法。 I recently published a project that allows PHP to obtain and interact with a real Bash shell, even through SSH. 我最近发布了一个项目,该项目允许PHP即使通过SSH也可以获取真实的Bash shell并与之交互。 Get it here: https://github.com/merlinthemagic/MTS 在这里获取它: https : //github.com/merlinthemagic/MTS

After downloading you would simply use the following code: 下载后,您只需使用以下代码:

$shell = \MTS\Factories::getDevices()->getRemoteHost('ip_address')->getShellBySsh('username', 'secretPassword');

//execute the grep command
$return1  = $shell->exeCmd("cat /full/path/to/logfile | grep \"someExpression\"");

echo $return1; //contains all the return that matched the grep expression

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM