Ssh.php 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118
  1. <?php
  2. /**
  3. * Suco_ssh 工厂类
  4. * Created by PhpStorm.
  5. * User: vanshao
  6. * Date: 2018/11/15
  7. * Time: 上午11:47
  8. */
  9. namespace App\Libs;
  10. class Ssh
  11. {
  12. /**
  13. * ssh 用户名
  14. * @var integer
  15. */
  16. protected static $_root;
  17. /**
  18. * ssh 密码
  19. * @var string
  20. */
  21. protected static $_pwd;
  22. protected static $_port = 22;
  23. /**
  24. * ssh IP
  25. * @var string
  26. */
  27. protected static $_ip;
  28. protected static $_connection;
  29. /**
  30. * @param $_ip
  31. * @param $_root
  32. * @param $_pwd
  33. * @return bool
  34. */
  35. public static function factory($_ip, $_root, $_pwd)
  36. {
  37. if (empty($_ip) || empty($_root) || empty($_pwd)) {
  38. return false;
  39. }
  40. self::$_connection = ssh2_connect($_ip, self::$_port);
  41. if (!ssh2_auth_password(self::$_connection, $_root, $_pwd)) {
  42. return false;
  43. }
  44. return true;
  45. }
  46. // protected static $sftp_resource;
  47. //
  48. // public static function sftp()
  49. // {
  50. // self::$sftp_resource = ssh2_sftp(self::$_connection);
  51. // }
  52. //
  53. // public static function sftp_mkdir($dir)
  54. // {
  55. // return ssh2_sftp_mkdir(self::$sftp_resource, $dir);
  56. // }
  57. /**
  58. * 远程执行命令
  59. * @param $cmd
  60. * @return bool|string
  61. */
  62. public static function exec($cmd)
  63. {
  64. $ret = ssh2_exec(self::$_connection, $cmd);
  65. // 获取结果
  66. stream_set_blocking($ret, true);
  67. // 返回结果
  68. return stream_get_contents($ret);
  69. }
  70. /**
  71. * 本地复制到运程
  72. * @param $local_file
  73. * @param $remote_file
  74. * @return bool
  75. */
  76. public static function send($local_file, $remote_file)
  77. {
  78. return ssh2_scp_send(self::$_connection, $local_file, $remote_file);
  79. }
  80. /**
  81. * 远程复制到本地
  82. * @param $remote_file
  83. * @param $local_file
  84. * @return bool
  85. */
  86. public static function receive($remote_file, $local_file)
  87. {
  88. return ssh2_scp_recv(self::$_connection, $remote_file, $local_file);
  89. }
  90. public static function dir_exists($dir)
  91. {
  92. $cmd = sprintf('if [ -d "%s" ]; then echo 1; else echo 0; fi', $dir);
  93. return substr(self::exec($cmd), 0, 1);
  94. }
  95. public static function mkdir($dir)
  96. {
  97. $cmd = sprintf('mkdir -p %s', $dir);
  98. return substr(self::exec($cmd), 0, 1);
  99. }
  100. }