program TelScript;
uses Windows, Sysutils, WinSock;
function Conectar(Host: string; Puerto: Integer): TSocket;
var
Address: u_long;
HostEnt: phostent;
Addr: sockaddr_in;
begin
Result:= INVALID_SOCKET;
Address:= inet_addr(Pchar(Host));
if Address = INADDR_NONE then
begin
HostEnt:= gethostbyname(PChar(Host));
if HostEnt <> nil then
Address:= u_long(HostEnt.h_addr_list^);
end;
if Address <> INADDR_NONE then
begin
Result:= socket(AF_INET, SOCK_STREAM, 0);
if Result <> INVALID_SOCKET then
begin
Addr.sin_family:= AF_INET;
Addr.sin_addr.S_addr:= Address;
Addr.sin_port:= htons(Puerto);
if connect(Result, Addr, Sizeof(Addr)) = SOCKET_ERROR then
begin
closesocket(Result);
Result:= INVALID_SOCKET;
end;
end;
end;
end;
function Enviar(Socket: TSocket; Str: string): Boolean;
begin
Result:= send(Socket,PChar(Str)^,Length(Str),0) <> SOCKET_ERROR;
end;
const
Alfanumericos = ['A'..'Z','a'..'z','0'..'9',':','-','<','>',' ','.'];
function EsperarStr(Socket: TSocket; Str: string; TimeOut: Cardinal): boolean;
var
i,j: integer;
s: string;
Tick: DWORD;
FDSet: TFDSet;
TimeVal: TTimeVal;
Buffer: array[0..1024] of Char;
begin
s:= '';
Tick := GetTickCount;
while not (pos(Str, s) > 0) do
begin
TimeVal.tv_sec := 0;
TimeVal.tv_usec := 500;
FD_ZERO(FDSet);
FD_SET(Socket, FDSet);
if select(0, @FDSet, nil, nil, @TimeVal) > 0 then
begin
fillchar(Buffer, sizeof(Buffer), 0);
i := recv(Socket, Buffer, sizeof(Buffer) - 1, 0);
if (i > 0) then
begin
for j:= 0 to i-1 do
if Buffer[j] in Alfanumericos then
s:= s + Buffer[j];
end else
break;
end
else if (GetTickCount - Tick) > TimeOut then
break;
end;
Result:= pos(Str, s) > 0;
end;
function Script(Socket: TSocket): Boolean;
begin
Result:= FALSE;
if EsperarStr(Socket,'ogin:',5000) then
begin
Enviar(Socket,'1234'+#13);
if EsperarStr(Socket,'assword:',5000) then
begin
Enviar(Socket,'1234'+#13);
if EsperarStr(Socket,'->',5000) then
begin
Enviar(Socket,'reboot'+#13);
if EsperarStr(Socket,'wait...',5000) then
begin
Result:= TRUE;
end;
end;
end;
end;
end;
procedure Mensaje(Str: string);
begin
Messagebox(0,PChar(Str),'TelScript',MB_OK);
end;
procedure Vamos;
var
WSAData: TWSADATA;
Socket: TSocket;
begin
if WSAStartup(MAKEWORD(1, 1), WSADATA) = 0 then
begin
Socket:= Conectar('192.168.1.1',23);
if Socket <> INVALID_SOCKET then
begin
if Script(Socket) then
Mensaje('El script termino con exito')
else
Mensaje('El script no pudo completarse');
closesocket(Socket);
end else
Mensaje('No puedo establecer la conexion con el router');
WSACleanup;
end;
end;
begin
Vamos;
end.