Advertisement
Guest User

Untitled

a guest
Jan 27th, 2019
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.37 KB | None | 0 0
  1. This is the best way I found to automatically run multiple commands or commands that might take longer then expected. NOTE: this assumes that no where in the output is there the text '[end]' otherwise the function will end prematurely. Hope this helps people.
  2.  
  3. <?php
  4. $ip = 'ip_address';
  5. $user = 'username';
  6. $pass = 'password';
  7.  
  8. $connection = ssh2_connect($ip);
  9. ssh2_auth_password($connection,$user,$pass);
  10. $shell = ssh2_shell($connection,"bash");
  11.  
  12. //Trick is in the start and end echos which can be executed in both *nix and windows systems.
  13. //Do add 'cmd /C' to the start of $cmd if on a windows system.
  14. $cmd = "echo '[start]';your commands here;echo '[end]'";
  15. $output = user_exec($shell,$cmd);
  16.  
  17. fclose($shell);
  18.  
  19. function user_exec($shell,$cmd) {
  20. fwrite($shell,$cmd . "\n");
  21. $output = "";
  22. $start = false;
  23. $start_time = time();
  24. $max_time = 2; //time in seconds
  25. while(((time()-$start_time) < $max_time)) {
  26. $line = fgets($shell);
  27. if(!strstr($line,$cmd)) {
  28. if(preg_match('/\[start\]/',$line)) {
  29. $start = true;
  30. }elseif(preg_match('/\[end\]/',$line)) {
  31. return $output;
  32. }elseif($start){
  33. $output[] = $line;
  34. }
  35. }
  36. }
  37. }
  38.  
  39. ?>
  40.  
  41. [EDIT BY danbrown AT php DOT net: Contains a bugfix supplied by (jschwepp AT gmail DOT com) on 17-FEB-2010 to fix a typo in a function name.]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement