>  기사  >  백엔드 개발  >  php实现telnet功能

php实现telnet功能

WBOY
WBOY원래의
2016-07-25 08:42:051866검색

使用php来实现telnet的连接、传递命令、获取返回值等功能!

telnet.php

  1. error_reporting(-1);
  2. class Telnet {
  3. var $sock = NULL;
  4. function telnet($host,$port) {
  5. $this->sock = fsockopen($host,$port);
  6. socket_set_timeout($this->sock,2,0);
  7. }
  8. function close() {
  9. if ($this->sock) fclose($this->sock);
  10. $this->sock = NULL;
  11. }
  12. function write($buffer) {
  13. $buffer = str_replace(chr(255),chr(255).chr(255),$buffer);
  14. fwrite($this->sock,$buffer);
  15. }
  16. function getc() {
  17. return fgetc($this->sock);
  18. }
  19. function read_till($what) {
  20. $buf = '';
  21. while (1) {
  22. $IAC = chr(255);
  23. $DONT = chr(254);
  24. $DO = chr(253);
  25. $WONT = chr(252);
  26. $WILL = chr(251);
  27. $theNULL = chr(0);
  28. $c = $this->getc();
  29. if ($c === false) return $buf;
  30. if ($c == $theNULL) {
  31. continue;
  32. }
  33. if ($c == "1") {
  34. continue;
  35. }
  36. if ($c != $IAC) {
  37. $buf .= $c;
  38. if ($what == (substr($buf,strlen($buf)-strlen($what)))) {
  39. return $buf;
  40. }
  41. else {
  42. continue;
  43. }
  44. }
  45. $c = $this->getc();
  46. if ($c == $IAC) {
  47. $buf .= $c;
  48. }
  49. else if (($c == $DO) || ($c == $DONT)) {
  50. $opt = $this->getc();
  51. // echo "we wont ".ord($opt)."\n";
  52. fwrite($this->sock,$IAC.$WONT.$opt);
  53. }
  54. elseif (($c == $WILL) || ($c == $WONT)) {
  55. $opt = $this->getc();
  56. // echo "we dont ".ord($opt)."\n";
  57. fwrite($this->sock,$IAC.$DONT.$opt);
  58. }
  59. else {
  60. // echo "where are we? c=".ord($c)."\n";
  61. }
  62. }
  63. }
  64. }
  65. /*
  66. ??÷??? ???
  67. $telnet = new telnet("192.168.0.1",23);
  68. echo $telnet->read_till("login: ");
  69. $telnet->write("kongxx\r\n");
  70. echo $telnet->read_till("password: ");
  71. $telnet->write("KONGXX\r\n");
  72. echo $telnet->read_till(":> ");
  73. $telnet->write("ls\r\n");
  74. echo $telnet->read_till(":> ");
  75. echo $telnet->close();
  76. */
复制代码
php, telnet


성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.