欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  后端开发

php telnet功能实现代码

程序员文章站 2022-04-17 15:24:26
...

本节内容: php telnet功能实例

文件:telnet.php

  1. error_reporting(-1);

  2. //telnet功能类

  3. class Telnet {
  4. var $sock = NULL;
  5. function telnet($host,$port) {
  6. $this->sock = fsockopen($host,$port);
  7. socket_set_timeout($this->sock,2,0);
  8. }
  9. function close() {

  10. if ($this->sock) fclose($this->sock);
  11. $this->sock = NULL;
  12. }
  13. function write($buffer) {
  14. $buffer = str_replace(chr(255),chr(255).chr(255),$buffer);
  15. fwrite($this->sock,$buffer);
  16. }
  17. function getc() {
  18. return fgetc($this->sock);
  19. }
  20. function read_till($what) {

  21. $buf = '';
  22. while (1) {
  23. $IAC = chr(255);
  24. $DONT = chr(254);
  25. $DO = chr(253);
  26. $WONT = chr(252);
  27. $WILL = chr(251);
  28. $theNULL = chr(0);
  29. $c = $this->getc();
  30. if ($c === false) return $buf;
  31. if ($c == $theNULL) {
  32. continue;
  33. }
  34. if ($c == "1") {
  35. continue;
  36. }
  37. if ($c != $IAC) {

  38. $buf .= $c;
  39. if ($what == (substr($buf,strlen($buf)-strlen($what)))) {
  40. return $buf;
  41. }
  42. else {
  43. continue;
  44. }
  45. } // bbs.it-home.org
  46. $c = $this->getc();

  47. if ($c == $IAC) {
  48. $buf .= $c;
  49. }
  50. else if (($c == $DO) || ($c == $DONT)) {
  51. $opt = $this->getc();
  52. // echo "we wont ".ord($opt)."\n";
  53. fwrite($this->sock,$IAC.$WONT.$opt);
  54. }
  55. elseif (($c == $WILL) || ($c == $WONT)) {
  56. $opt = $this->getc();
  57. // echo "we dont ".ord($opt)."\n";
  58. fwrite($this->sock,$IAC.$DONT.$opt);
  59. }
  60. else {
  61. // echo "where are we? c=".ord($c)."\n";
  62. }
  63. }
  64. }
  65. }
  66. /*

  67. 使用方法
  68. telnet类的调用
  69. $telnet = new telnet("192.168.0.1",23);
  70. echo $telnet->read_till("login: ");
  71. $telnet->write("kongxx\r\n");
  72. echo $telnet->read_till("password: ");
  73. $telnet->write("KONGXX\r\n");
  74. echo $telnet->read_till(":> ");
  75. $telnet->write("ls\r\n");
  76. echo $telnet->read_till(":> ");
  77. echo $telnet->close();
  78. */
复制代码