1

I'm new to the PHP world but wanting to set up a relatively simple PHP script that will execute shell commands to a remote host via ssh2_exec when a user presses a button on the web page. I'd like this to be processed via POST as opposed to GET. I want to avoid web CGI with bash scripts.

After reviewing this documentation on ssh2_exec I was able to gather somewhat of an idea of what needs to be done, but I still am needing quite a bit of help.

To help better understand what I'm trying to accomplish, let me explain. I'm looking to have two text fields and a submit button on a page. Let's call these text fields $var1 and $var2. I want the user to fill out both text fields, hit submit, and that submit a command to a remote server that looks like:

# [root@server] $var1 /home/$var2.sh

Now I'm not anywhere near where I need to be, but the following is the (non-working) code I've compiled on my own and looking for ways to make it work, or improvements. Also I realize connecting to a remote server and running commands as root via a PHP script is not a good idea. But this is purely for development/testing and nothing production. I'm just trying to familiarize myself with the process. Anyway, here is what I have:

<?php
    $connection = ssh2_connect('192.168.1.1', 22);
    ssh2_auth_password($connection, 'root', 'password');

    if (isset($_POST['button']))
    {
         $stream = ssh2_exec($connection, 'touch /root/test/test.txt');
    }
?>
<html>
<body>
    <form method="post">
    <p>
        <button name="button">Touch</button>
    </p>
    </form>
</body>

Again, I'm sure the above code looks atrocious and entirely incorrect to a developer, but as I said I'm new to PHP so this was me just trying my best on my own.

So with that said, if anyone has any type of insight, helpful links, tips, anything - it would be greatly appreciated!

4

2 回答 2

1

看到那个帖子:其他帖子

<?php
include('Net/SSH2.php');

$ssh = new Net_SSH2('www.domain.tld');
if (!$ssh->login('username', 'password')) {
    exit('Login Failed');
}

echo $ssh->exec('pwd');
echo $ssh->exec('ls -la');
?>

使用这个库应该可以帮助你完成你所需要的。

只要是为了测试。否则,我会使用XML-RPC来调用服务器端程序

于 2014-09-18T21:00:29.690 回答
0

我将尝试解释您需要完成的步骤才能完成您想要的。

  1. 您将需要在您网站的某个地方创建一个 HTML 页面。这可能只是一个index.html

    <html> <body> <form method="post"> <input type="text" id="text1"><br> <input type="text" id="text2"><br> <button name="button">Touch</button> </form> </body>

  2. 您将不得不研究一种称为 JavaScript 的语言。JavaScript 将允许您获取在文本框中输入的值并通过称为 Ajax 的东西将它们发送到 PHP。

    http://www.w3schools.com/ajax/ajax_intro.asp

    简而言之,Ajax 是您的网站与服务器和客户端进行通信的一种方式。您可以将数据从客户端(您的 HTML 页面)发送到您的服务器 (PHP) 并在那里处理数据。

    但是,还有另一种选择,您可以使用当前代码并向标签添加action属性<form>并将用户重定向到您的 PHP 页面,然后根据$_POST需要使用数据。

    这是一个例子:http ://www.w3schools.com/php/php_forms.asp

  3. 一旦完成上述步骤,无论是 Ajax 发布还是表单发布,您现在都可以在 PHP 中处理所有值。

于 2014-09-18T20:56:43.423 回答