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!