I am currently trying to figure out how to connect to another server via SSH using PHP's shell functions. I have a site where I have to pass data from PHP to a custom command line program, then return the output. On the old server I was using, this was possible via the exec() function:

$cmd = '/path/to/custom/program "arg1", "arg2", "arg3"';
exec($cms, $output);

$output, of course, would then hold the data that my program returned.

I am now in a position where the host will not allow me to run my custom program. PHP's shell functions, however, are still available. The host suggested I set up PHP to SSH into a different server, run the commands I need to run, and then return the output. This seems like an incredibly backwards way of doing things, but what do I know?

My specific question relates to how I would go about passing the login information to the exec() command. For example, when I connect to any SSH server manually, I put in:

[INDENT]ssh myserver.com -l myusername[/INDENT]

And then I see:

[INDENT]myusername@myserver.com's password:[/INDENT]

If I were to pass "ssh myserver.com -l myusername" as the command to exec(), how would I then give it the password? After that, how would I then know that I am properly authenticated and connected so I can run the command for my program?

Oh, and also, I do not have access to the ssh2 functions in PHP, nor would I be able to install that extension.

    Create a public key to login without password. Hope you have ssh access to the server so you can create the key.

    1. Create public key (run "ssh-keygen -t dsa" which should create key -> .ssh/id_dsa.pub

    2. Copy the created public key as ~username/.ssh/authorized_keys to your server

    3. thats it. Try it: ssh myusername@myserver.com 'command-to-run'

    If that does'nt work, does your own server have apache running? You could just send a request over http (with proper authorization ofcourse if the script is something that only you can access) and get the response back. RESTful services are hip and cool today you know 😉

      9 days later
      Write a Reply...