Run a command using Telnet

telnetcmd.are
/* DESC: This script runs a shell command using telnet.
 *       Only the first response line is returned.
 *       Don't forget to enable the telnet server
 *       For special chars in command string use escape: apostrophe = "\x27"
 * Copyright (C) 2014 NetModule AG, Switzerland, rfa
 */
 
string telnet(ip, port, user, password, cmd)
{
  if ((sock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) return NULL;
  if (connect(sock, ip, port) < 0) return NULL;
  try {
    if ((buf = recv(sock)) == NULL || strlen(buf) < 3) throw NULL;
    buf = explode(buf);
    if (buf[0] == "\xff") // is command
    {
      if (buf[1] == "\xfd" && buf[2] == "\d031") { //negotiate
        if (send(sock, "\d255\d251\d031") == -1) throw NULL;
        if (send(sock, "\d255\d250\d031\d000\d080\d000\d024\d255\d240") == -1) throw NULL;
      } else {
        for (i = 0; i < strlen(buf); i++)
          if (buf[i] == "\xfd") buf[i] = "\xfc";
          else if (buf[i] == "\xfb") buf[i] = "\xfd";
          if (send(sock, implode(buf)) == -1) throw NULL;
          }
    }
    if ((buf = recv(sock)) == NULL || strlen(buf) < 1) throw NULL; // user ?
    if (send(sock, strcat(user, "\r\n")) == -1) throw NULL;
    if ((buf = recv(sock)) == NULL || strlen(buf) < 1)throw NULL; // password ?
    if (send(sock, strcat(password, "\r\n")) == -1) throw NULL;
    while((s = select(sock, 1)) > 0 && (buf = recv(sock)) != NULL && strlen(buf) > 0)
      if (s == -1) throw NULL; //ignore all garbage
      if (send(sock, strcat(cmd, "\r\n")) == -1) throw NULL;  //send command
      rbuf ="";
    while((s = select(sock, 1)) > 0 && (buf = recv(sock)) != NULL && strlen(buf) > 0){
      if (s == -1) throw NULL; 
      else rbuf = strcat(rbuf, buf); // collect return
    }
    rbuf = right(rbuf, strlen(rbuf) - strlen(cmd) - 2); //cut cmd
    if (pos = strrchr(rbuf, "\r"))
      rbuf = left(rbuf, pos);
    throw rbuf;
  } catch (ret) {
    close (sock);
    return ret;
  }
}
 
 
printf("date = <%s>\n", telnet("192.168.1.1", 23, "root", "password", "date"));
	// show date
 
printf("uptime = <%s>\n", telnet("192.168.1.1", 23, "root", "password", "uptime | awk \x27{print $8}\x27")); 
	//CPU load. Values 0.00-1.00 0=none, max=1.00(100%)
 
printf("free mem = <%s>\n", telnet("192.168.1.1", 23, "root", "password", "free | grep Total | awk \x27{print $3/$2}\x27"));
    //show free memory Values 0-1 0=none, max=1(100%)
 
printf("ps = <begin>%s<end>\n", telnet("192.168.1.1", 23, "root", "password", "ps"));
	// show processes