Sunday, August 30, 2009

[PHP] - Connect to Unix / Linux server using SSH from Windows PC

Setting up public key authentication:

1.  Login to the unix server you want to connect using putty.
2.  mkdir .ssh (there is a dot before ssh)
3.  cd .ssh
4.   ssh-keygen -t rsa -f mykey
5.  Enter passphrase as test
6.  ls -al -> you will find two files mykey , mykey.pub
7.  cat mykey.pub >>authorized_keys
8.  cat mykey
9.  Copy what you get on screen to notepad and save it as "c:\mykey" (within quotes)
10.  cat mykey.pub
11.  Copy what you get on screen to notepad and save it as "c:\mykey.pub" (within quotes)


PHP Code:

<?php

      // Functions to connect to Unix Server using SSH


      $methods = array(
      'kex' => 'diffie-hellman-group1-sha1',
      'client_to_server' => array(
      'crypt' => 'aes256-cbc',
      'comp' => 'none',
      'mac' => 'hmac-sha1'),
      'server_to_client' => array(
      'crypt' => 'aes256-cbc',
      'comp' => 'none',
      'mac' => 'hmac-sha1'));

      $callbacks = array('disconnect' => 'my_ssh_disconnect');

      // Function to run a command on the unix server

      function run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command)
      {
          $connection = ssh2_connect($ssh_host, 22, $methods, $callbacks);
          if (!$connection) die('Connection failed');
          if (ssh2_auth_pubkey_file($connection, $user_name, $keyfilename.".pub", $keyfilename, 'test'))
          {
            echo "Public Key Authentication Successful as user: $user_name
";
          }
          else
          {
            die('Public Key Authentication Failed');
          }

          $stream = ssh2_exec($connection, $ssh_command);
          $i=0;
          stream_set_blocking($stream, true);
          $line = stream_get_line($stream, 1024, "\n");
          while (!feof($stream))                                                                              
          {
                  echo $line.'
';
                  $line = stream_get_line($stream, 1024, "\n");
                  $i++;
          } 
          echo "Count : ".$i;
          flush();
          unset($stream); 
      }

      function my_ssh_disconnect($reason, $message, $language)
      {
            printf("Server disconnected with reason code [%d] and message: %s\n",
            $reason, $message);
      }



      // Main Code

      $user_name = "USERID";
      $keydir = "c:\\";
      $search_string = 'needle';
      $keyfilename= $keydir.'mykey';
      $ssh_host = "foo.bar.com";
      $ssh_command = 'grep "'.$search_string.'" /haystack/*.log';
      run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command);

      $ssh_command = 'ls -al';
      run_cmd($ssh_host, $user_name, $keyfilename, $ssh_command);
?>
Bookmark and Share

1 Comments:

Anonymous vichu said...

hi this is vishwa.Your blog is really worthy for job seekers as well for me. Go ahead with your job.. thank you.

March 25, 2010 2:33 PM  

Post a Comment