PHP SSH2 code

I’ve had a need to use the PHP SSH2 PECL recently (working on making a product, at work, more efficient) And thought I would share some of the preliminary code. You can find it here: vpssh.phps

The most interesting thing is not vpssh_core or it’s exec (though it’s good code) the really interesting thing is the vpssh_tunnel class and the accompanying examples at the top of the file. This really shows some advanced usage of ssh2_tunnel that you can’t really find anywhere else.

It’s just the beginnings of some useful code, but it’s probably a huge jumping off point for anyone seriously looking into the ssh2 pecl functionality. Oh, it also works with both password and key based authentication.

This code is less than 12 hours old, and it works for me so far, YMMV. Feedback welcome … or not… Whatever. Hope it helps someone out. And I hope it helps me out later when I need this kind of thing again.

6 thoughts on “PHP SSH2 code

  1. Just what I've been looking for. There's a sad lack of practical examples of usage of the ssh2_tunnel. It's a pity mysql can't be connected directly through the tunnel to save having to use a local port, isn't it?

    • Glad it helped! And yes on both counts — the lack of useful examples is frustrating AND it would be nice to be able to tell mysql_p?connect() to use it like that. Actually what would be the most useful to most people would be to have ssh2_socket_create_pair() a la socket_create_pair()

  2. One thing: since the tunnel script once created just sits there waiting, it can't be used except as a background task of some kind. So are you running it via the commandline, or forking a process from PHP?

    If the former I guess it's an improvement on the ssh command because you can get passwords etc from a database and that makes life easier, but there's still a potential issue with managing the allocation of ports, isn't there? Are you using some kind of IPC so your PHP components all know what's going on?

    • This is just meant to be some helpful started code for a cog in a bigger application so how you wanted to go about the rest of implementation really depends on what you're doing. Probably the simplest thing would be to read the user/pass from STDIN, and keep trying an mt_rand(min,max) port possibly on multiple localhost addresses (did you know you can bind lots of 127 ip addresses to lo?) and communicate the found ip/port on STDOUT before firing up the loop. This way your controlling process could write/read relevant information from proc_open() pipes. There of course are lots of other things you could do depending on your needs. I would avoid using an IPC socket pair except maybe as a heartbeat monitor to make sure the controlling process hasn't gone away (but even that is dependent on how you're using the thing.) Also I've documented how to use password authentication with the SSH command in another post on this blog which you might be interested in reading.

Leave a Reply