Creating web interface to access your remote Linux servers

Posted by: Mo Mughrabi No Comments »

Its been a while since last I've posted anything but am here trying to keep up with many websites. Any who, Recently I was requested by one of my clients to create a web interface to help the none technical restart apache, mysql and do some monitoring on different servers.

so, first what I did is generate a key to create secure channels between the servers in order to connect without prompting for password (click here for steps). Then, I faced some trouble writing the PHP code which will connect and do these tasks and after long day of surfing and some help from my team (Basant) we finally nailed it.

First, you will need to install openssl (openssl-devel), then download and compile libssh2 and then you will need to add the extension in your PHP.ini (click here for PHP ssh2 installation manual) and here is a sample code on how it can be done in PHP.

  1.  
  2.  
  3. // Notify user if the server terminates the connection
  4. function my_ssh_disconnect($reason, $message, $language)
  5. {
  6. printf("Server disconnected with reason code[%d] and
  7. message: %s\n" ,$reason, $message);
  8. }
  9.  
  10. $methods = array(
  11. 'kex' => 'diffie-hellman-group1-sha1',
  12. 'client_to_server' => array(
  13. 'crypt' => '3des-cbc',
  14. 'comp' => 'none'),
  15. 'server_to_client' => array(
  16. 'crypt' => 'aes256-cbc,aes192-cbc,aes128-cbc',
  17. 'comp' => 'none'));
  18.  
  19. $callbacks = array('disconnect' => 'my_ssh_disconnect');
  20.  
  21. $connection = ssh2_connect('domain_name.com', 22, $methods,
  22. $callbacks) or die('Couldnot locate the ssh2');
  23. if (!$connection) die('Connection failed');
  24. if (ssh2_auth_password($connection, 'linux_user',
  25. 'linux_password')) {
  26. echo "Authentication Successful!\n\n";
  27. $shell=ssh2_shell($connection, 'bash') or die("error");
  28. // fwrite will send execute commands and return value in
  29. $shell
  30. fwrite( $shell, "/etc/init.d/httpd restart\n");
  31.  
  32. // this will look the $shell array and print the
  33. returned value.
  34. while($line = fgets($shell)) {
  35. flush();
  36. echo $line."";
  37. }
  38.  
  39. fclose($shell); // close connection
  40. }else{
  41. echo "Error with connection\n";
  42. }
  43.  
  44. ?>
WP Theme & Icons by N.Design Studio
Entries RSS Comments RSS Login