I was trying to do an XML dump with MediaWiki for a friend, and the tools MediaWiki provides to do it requires shell access — which my friend does not have in his hosting package. So I tried using phpshell, but got annoyed that it would freeze anytime I executed something that required user input. After much thought, I devised a way to create an SSH shell using PHP (sorta) that I could use. Heres how you can do it too.
PHP can (usually) execute arbitrary executable files on the server that it resides on. If the executable forks, then it can open other programs or connect to remote resources, without hanging the PHP connection. I’ve written a program that does this, and executes a statement that connects to a remote SSH server, creates a tunnel to it, and opens a shell on that tunnel so that a user on the remote SSH server can connect to that port and use the shell. The statement looks like this:
netcat -l -p 20000 -s 127.0.0.1 -e "/bin/bash -i" | ssh -NR 20001:localhost:20000 username@hostname -o "StrictHostKeyChecking false" -i key_file_name
You can connect to this shell by doing a
netcat localhost 20001
on the remote SSH server. You need to setup an SSH key on both servers so that the authentication doesn’t ask you for a password at all (see below). Of course, if those programs don’t exist on the remote server then this wont work (however, I have included a compiled version of gnu-netcat with the program that you can use).
This code works, but is still mostly a ‘proof of concept’.
- You must be able to upload files to the server and ensure they are executable (though, the software tries to set the executable bits if it is not the case)
- You must be either able to compile files in a executable format that the server can execute, or you must be able to compile files on the server itself (in which case, you probably don’t need this program!).
- The user that the webserver (or the php CGI script) is running as must be able to write to a file
- You need an accessible SSH server setup somewhere that you can add user accounts to
- Forwarding must be enabled (default: yes)
- Public key authentication must be enabled (default: yes)
- It needs to have netcat installed
- I used Linux to set this up