I've written something like this a few years ago. I don't advertise this any
longer, you can have a free copy or parts of the code if you wish.
Description is on http://homepages.fh-giessen.de/~hg12799
Contact me out of the list.

GetCmd below get's the position of a command within a script. I parse a
script line by line and when a command (html like in <> brackets) is the
next part of the line, DoCmd is called which executes the command. 
I think you can exchange or add the string you wish to respond to in getcmd,
so just add a command without brackets if what you want is to just respnd to
a command line from the terminal. 

Looking back, it's propably the worst spaghetti code I've ever written ;-).
But it's surprisingly still working ok in the environment I've written it
for (backup of about 150 network devices several times a day and recovery)


Benjamin Stadin


function TBenScript.GetCmdPos(LineString: String): Integer;  // Führt
Kommando aus und liefert StringPosition des Kommandos
var CmdPos: Integer; // erstes Kommando in Zeile
    ThisPos: Integer;  // aktuelle geparsetes Kommando
  //  FirstCommand parsed welches abgeklapperte Kommando das erste ist
begin
  CmdPos := 0; // Kein Vorgängerwert von Pos = logisch 0 für Result
  FirstCommand := '';
  NoReturn := False;
  CmdLength := 0;

    if Pos('<TELNET>',Uppercase(LineString)) > 0 then begin
     CmdPos := Pos('<TELNET>',Uppercase(LineString));
     FirstCommand := '<TELNET>';
     NoReturn := True; // NoReturn = dieser befehl braucht keinen return,
wird aus scriptline entfernt
    end;

    if Pos('<WAIT>',Uppercase(LineString)) > 0 then begin
     CmdPos := Pos('<WAIT>',Uppercase(LineString));
     FirstCommand := '<WAIT>';
     NoReturn := True;
    end;

    if Pos('<LINESTOFILE',Uppercase(LineString)) > 0 then begin
     CmdPos := Pos('<LINESTOFILE',Uppercase(LineString));
     CmdLength := Pos('>',ScriptLine);
     FirstCommand := '<LINESTOFILE';
     NoReturn := True;
    end;

    if Pos('</LINESTOFILE>',Uppercase(LineString)) > 0 then begin
     CmdPos := Pos('</LINESTOFILE>',Uppercase(LineString));
     FirstCommand := '</LINESTOFILE>';
     hauptform.telnet.WriteStr(RetSeq);
  //   NoReturn := True;
  // hier nicht, weil emulvt erst nach zeichenübergabe FSave2File ändert 
    end;

    if Pos('<FILETOLINE',Uppercase(LineString)) > 0 then begin
     CmdPos := Pos('<FILETOLINE',Uppercase(LineString));
     CmdLength := Pos('>',ScriptLine);
     FirstCommand := '<FILETOLINE';
     NoReturn := True;
    end;

    if Pos('<NTINIT>',Uppercase(LineString)) > 0 then begin
     CmdPos := Pos('<NTINIT>',Uppercase(LineString));
     FirstCommand := '<NTINIT>';
     NoReturn := True;
    end;

    if Pos('</TELNET>',Uppercase(LineString)) > 0  then begin
     ThisPos := Pos('</TELNET>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('</TELNET>',LineString);
      FirstCommand := '</TELNET>';
      NoReturn := True;
     end;
    end;

    if Pos('<COMPORT>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<COMPORT>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<COMPORT>',Uppercase(LineString));
      FirstCommand := '<COMPORT>';
      NoReturn := True;
     end;
    end;

    if Pos('</COMPORT>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('</COMPORT>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('</COMPORT>',Uppercase(LineString));
      FirstCommand := '</COMPORT>';
      NoReturn := True;
     end;
    end;

    if Pos('<LOCALIP>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<LOCALIP>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<LOCALIP>',Uppercase(LineString));
      FirstCommand := '<LOCALIP>';
     end;
    end;

    if Pos('<LOCALSUBNET>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<LOCALSUBNET>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<LOCALSUBNET>',Uppercase(LineString));
      FirstCommand := '<LOCALSUBNET>';
     end;
    end;

    if Pos('<RECOVERY>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<RECOVERY>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<RECOVERY>',Uppercase(LineString));
      FirstCommand := '<RECOVERY>';
      NoReturn := True;
     end;
    end;

    if Pos('<CALCIP>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<CALCIP>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<CALCIP>',Uppercase(LineString));
      FirstCommand := '<CALCIP>';
     end;
    end;

    if Pos('<PORT>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<PORT>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<PORT>',Uppercase(LineString));
      FirstCommand := '<PORT>';
      NoReturn := True;
     end;
    end;

    if Pos('<FILENAME>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<FILENAME>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<FILENAME>',Uppercase(LineString));
      FirstCommand := '<FILENAME>';
     end;
    end;

    if Pos('<DATE>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<DATE>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<DATE>',Uppercase(LineString));
      FirstCommand := '<DATE>';
     end;
    end;

    if Pos('<DATETIME>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<DATETIME>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<DATETIME>',Uppercase(LineString));
      FirstCommand := '<DATETIME>';
     end;
    end;

// #99 = c, #122 =z
    if Pos('<GOTOTOP>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<GOTOTOP>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<GOTOTOP>',Uppercase(LineString));
      FirstCommand := '<GOTOTOP>';
      NoReturn := True;
     end;
    end;

    if Pos('<LOGINPW>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<LOGINPW>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<LOGINPW>',Uppercase(LineString));
      FirstCommand := '<LOGINPW>';
      NoReturn := True;
     end;
    end;

    if Pos('<ENABLEPW>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<ENABLEPW>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<ENABLEPW>',Uppercase(LineString));
      FirstCommand := '<ENABLEPW>';
      NoReturn := True;
     end;
    end;

    if Pos('<USERNAME>',Uppercase(LineString)) > 0 then begin
     ThisPos := Pos('<USERNAME>',Uppercase(LineString));
     if (ThisPos < CmdPos) or (CmdPos = 0) then begin
      CmdPos := Pos('<USERNAME>',Uppercase(LineString));
      FirstCommand := '<USERNAME>';
      NoReturn := True;
     end;
    end;

  Result := CmdPos;
end;


procedure TBenScript.DoCmd(Command: String);
var Attributes, i, x, instance, CmdLength: Integer;
    Str, s, datum, zeit, tempstr: String;
    PhraseFound, SubStringCollecting: Boolean;
    FileLine: textFile;
begin
  with hauptform do begin
    if FirstCommand = '<TELNET>' then begin
//     telnet.Disconnect;
     if not Analyze then begin
       ResyncGrid(True);
       telnet.Disconnect;
       telnet.Clear;
       telnet.HostName := host;
       if RecoveryInProgress then
        ConnectionSettings('', False);
    //   else
    //    ConnectionSettings('bla', False);
       if telnet.IsSSHSet then
        telnet.TnConn.SetSSHUserPass(SSHUserName, SSHPw);
       telnet.Connect;
       if Delay(300) then // Geraät braucht zum aktivieren
       if not telnet.IsConnected then begin
        EventLogger('Failed to connect to '+host, False);
        BreakCycle := True;
        exit;
       end;
       ConnectionType := 'TELNET';
     end
     else begin
     AnList('<telnet> #Connect telnet to '+host,True);
    end;
    end;

    if FirstCommand = '</TELNET>' then begin
     if (not Analyze) and (not BreakCycle) then begin
  //    Delay(1000); // Warten, damit alles in Log geschrieben wird
  //     if telnet.IsSSH then
  //      telnet.IsSSH := False;
       telnet.Disconnect;
      Delay(300);
      ConnectionType := '';
      ResyncGrid(True);
     end
      else if not BreakCycle then begin
      AnList('</telnet> #Disconnect telnet session', True);
     end;
     end;

    if FirstCommand = '<COMPORT>' then begin
     if not Analyze then begin
      ResyncGrid(True);
      telnet.Clear;
      telnet.WriteStr('Connecting through serial interface... ');
       if RecoveryInProgress then
        ConnectionSettings('', True);
     if not ComPort.Connected then
      if not BreakCycle then try
      ComPort.Open;
      Delay(200); // Geraät braucht zum aktivieren
     except
      EventLogger('Unable to open com port!', False);
      telnet.WriteStr('Unable to open com port! Cancelling current device...
');
      BreakCycle := True;
      exit;
     end;
     ConnectionType := 'TERMINAL';
     end
      else begin
      AnList('<comport> #Connect with com port',True);
     end;
    end;

    if FirstCommand = '<NTINIT>' then begin
    if not Analyze then begin
     ResyncGrid(True);
     telnet.WriteStr('Please wait for Windows to reinitilaize your NIC. This
may take a minute or so...'+#13#10);
     hauptform.NetWorkVarInit;
      if localhost = '0.0.0.0' then
      repeat
       NetworkVarInit;
       Sleep(100);
       Delay(1000);
      until
       localhost <> '0.0.0.0';
      Sleep(2000);
      hauptform.NetWorkVarInit;
     end
      else begin
      AnList('<ntinit> #Reinitialize Windows NT/2000/XP Network. This takes
1-2 minute(s)!',True);
     end;
    end;

    if FirstCommand = '</COMPORT>' then begin
    if not Analyze then begin
     ResyncGrid(True);
     if ComPort.Connected then
      ComPort.Close;
     ConnectionType := '';
    end
     else begin
     AnList('</comport> #Disconnect com port',True);
     end;
    end;

    if FirstCommand = '<LINESTOFILE' then begin
     Str := ScriptLine;
     CmdLength := Pos('>', Str);
     Delete(Str, CmdLength, Length(Str)-1);
     SubStringCollecting := False;
     s := ''; // string für dateinamen
     tempstr := ''; //string für dateiname etc
     Delete(Str,1, Pos('=', Str));
     x := 0;
     for i := 0 to CmdLength -1 do begin
       if Str[i] = '"' then begin
         inc(x);
         if x mod 2 = 0 then // alle 2. " ergeben ein teilstring
           SubStringCollecting := False
         else
           SubStringCollecting := True;
       end;
       if SubStringCollecting then begin
         if Str[i] <> '"' then
           s := s + Str[i];
       end
       else begin
         tempstr := tempstr + Str[i];
         if Pos('hostname', tempstr) > 0 then begin
           s := s + host;
           tempstr := '';
         end;
         if Pos('date', tempstr) > 0 then begin
           s := s + FormatDateTime('yy-mm-dd', Now);
           tempstr := '';
         end;
         if Pos('time', tempstr) > 0 then begin
           s := s + FormatDateTime('hh-mm-ss', Now);
           tempstr := '';
         end;
       end;
     end;
     Str := s;
    // showmessage('|'+s+'|');
     if not Analyze then begin
      ResyncGrid(True);
      try
        telnet.save2line := False;
        telnet.Save2LineFileName := tftproot+'\'+Str;
        if DirectoryExists(ExtractFilePath(tftproot+'\'+Str)) then
          telnet.Save2Line := True;
      except
      end;
     // Delay(200);
     end
     else begin
       AnList('<linestofile="'+Str+'"> #Start saving telnet/terminal output
to '+tftproot+'\'+Str,True);
       if not DirectoryExists(ExtractFilePath(tftproot+'\'+Str)) then
         eventlogger('File '+tftproot+'\'+Str+' doesn''t exist!
<LINESTOFILE> failed!', False);
     end;
    end;

    if FirstCommand = '<FILETOLINE' then begin
     Str := ScriptLine;
     i := Pos('"', Str);
     Delete(Str,1,i); // erstes " löschen
     i := Pos('"', Str);
     Delete(Str,i,Length(Str)-1); // ab zweites " bis ende des Strings
löschen
     if not Analyze then begin
      if FileExists(tftproot+'\'+Str) then begin
       AssignFile(FileLine, tftproot+'\'+Str);
       reset(FileLine);
       While not EOF(FileLine) or BreakCycle do begin
        inc(RowCounter);
        ResyncGrid(False);
        Str := '';
        readln(FileLine,Str);
        if Pos('!', Str) <> 1 then begin
         BufferIsFree := False;
         Timer3.Enabled := False;  // auf 500 msec zurücksetzen
         Timer3.Enabled := True;
         if not BreakCycle then
          SendToTelnetOrTerminal(Str+RetSeq)
         else
          exit;
        end;
       end;
        if IOResult <> 0 then
        CloseFile(FileLine);
      end
       else eventlogger('File '+tftproot+'\'+Str+' doesn''t exist!
<FILETOLINE> failed!', False);
     end
     else begin  // ANalyze Teil
      AnList('<filetoline"'+Str+'"> #Send text from file '+tftproot+'\'+Str
+' to telnet/terminal',True);
      if FileExists(tftproot+'\'+Str) then begin
       AssignFile(FileLine, tftproot+'\'+Str);
       reset(FileLine);
       While not EOF(FileLine) or BreakCycle do begin
        // debug
        inc(RowCounter);
        Str := '';
        readln(FileLine,Str);
        if Pos('!', Str) <> 1 then begin
         BufferIsFree := False;
         Timer3.Enabled := False;  // auf 500 msec zurücksetzen
         Timer3.Enabled := True;
         if not BreakCycle then
          Anlist(Str, True)
         else
          exit;
        end;
       end;
       if IOResult <> 0 then
        CloseFile(FileLine);
      end
        else if not RecoveryInProgress then
          eventlogger('File '+tftproot+'\'+Str+' doesn''t exist!
<FILETOLINE> failed!', False);
     end;
    end;


    if FirstCommand = '</LINESTOFILE>' then begin
     if not Analyze then begin
     try
      ResyncGrid(True);
  //    Delay(200);
      telnet.Save2Line := False;
      telnet.WriteStr(RetSeq);
     except
     end;
     end
     else begin
      AnList('</linestofile> #Stop saving telnet/terminal to file',True);
     end;
    end;

     if FirstCommand = '<LOGINPW>' then begin
     if not Analyze then begin
      ResyncGrid(True);
      PhraseFound := False;
       Sleep(100);
     for x:=0 to 1 do begin
      instance := x;
      for i:=0 to telnet.Rows do begin
       Str:=telnet.Screen.Lines[i].Txt;
       if (Pos('assword',Str) > 0) and (Pos('assword',Str) < 5) then
        PhraseFound := True;
      end;
       if not PhraseFound then begin
        if LocateLoginPw then
         Delay(200);
        if not BreakCycle then begin
         If LocateLoginPw then begin
          SendToTelnetOrTerminal(RetSeq);
          Delay(500);
         end;
        end
        else
         exit;
       end;  // i
      end; // x
     if (instance = 1) or PhraseFound then
      if not BreakCycle then
      SendToTelnetOrTerminal(LoginPw+RetSeq);
     end
     else begin
      AnList('<loginpw> #Send Login password',True);
     end;
     end;


    if FirstCommand = '<ENABLEPW>' then begin
     if not Analyze then begin
      ResyncGrid(True);
      if not BreakCycle then
      SendToTelnetOrTerminal(EnablePw+RetSeq);
     end
     else begin
      AnList('<enablepw> #Send Enable password', True);
     end;
     end;

    if FirstCommand = '<USERNAME>' then begin
     if not Analyze then begin
      ResyncGrid(True);
      if not BreakCycle then
       SendToTelnetOrTerminal(TELNETUSERNAME+RetSeq);
     end
     else begin
      AnList(TelnetUserName+' #Send Username', True);
     end;
     end;

    if FirstCommand = '<WAIT>' then begin
     if not Analyze then begin
      ResyncGrid(True);
        if AnalyzerForm.StringGrid1.Row <
AnalyzerForm.StringGrid1.RowCount-1 then
        AnalyzerForm.StringGrid1.Row := AnalyzerForm.StringGrid1.Row+1;
     CheckForData := true;
     HaveData := True;
     Timer1.Enabled := True;
     repeat
      Sleep(100);
      Delay(500);
     until
      (not CheckForData) or BreakCycle;
     end
     else begin                                            // nocht hier
resyncen !!!!
      AnList('<wait> #Wait until device doesn''t send + 15 seconds', True);
     end;
    end;

    if FirstCommand = '<CALCIP>' then begin
     if not Analyze then begin
     if not BreakCycle then
       SendToTelnetOrTerminal(RecoveryHost);
     end
     else
      AnList(RecoveryHost, False);
    end;


    if FirstCommand = '<LOCALSUBNET>' then begin
     if not Analyze then begin
      if not BreakCycle then
       SendToTelnetOrTerminal(Subnet);
     end
     else
      AnList(Subnet,False);
    end;

    if FirstCommand = '<DATE>' then begin
     if not Analyze then begin
       if (Pos(UpperCase('\<DATE>'), UpperCase(scriptline)) > 0) or
(Pos(UpperCase('/<DATE>'), UpperCase(scriptline)) > 0) then
       if not DirectoryExists(tftproot+'\'+verzzeit) then  begin
         createdir(tftproot+'\'+verzzeit);
       end;
       if not BreakCycle then
       SendToTelnetOrTerminal(verzzeit);  // Verzeichniss bei InitTheShit
erstellt
     end
     else
      AnList(verzzeit, False);
    end;

    if FirstCommand = '<DATETIME>' then begin
     if not Analyze then begin
      if not BreakCycle then
      SendToTelnetOrTerminal(FormatDateTime('yy-mm-dd-hh-mm-ss-', Now));
     end
     else begin
      Str := FormatDateTime('yy-mm-dd-hh-mm-ss-', Now);
      AnList(Str, False);
     end;
    end;

    if FirstCommand = '<FILENAME>' then begin
     if not Analyze then begin
      if not BreakCycle then
      SendToTelnetOrTerminal(LocalCfgFileName);
     end
     else
      AnList(LocalCfgFileName, False);
    end;

    if FirstCommand = '<PORT>' then begin
     if not Analyze then begin
     if not BreakCycle then
     SendToTelnetOrTerminal(port); //Leerzeichen weil alle vorangehenden
Zeichen der Zeile bearbeitet (Delete...)
     end
     else
      AnList(port, False);
     end;

    if FirstCommand = '<LOCALIP>' then begin
     if not Analyze then begin
     if not BreakCycle then
     SendToTelnetOrTerminal(localhost);
     end
     else
      AnList(localhost, False);
     end;

    if FirstCommand = '<GOTOTOP>' then begin
     if not Analyze then begin
      ResyncGrid(True);
      for i:=0 to 5 do
       if not BreakCycle then
       SendToTelnetOrTerminal(#26);       // # 11 = Strg
     end
     else begin
      AnList('<gototop> #Send Strg+Z 6 times',True);
     end;
    end;

    if FirstCommand = '<RECOVERY>' then begin
     if not Analyze then begin
      ResyncGrid(True);
      if FileExists(PCHar(tftproot+'\recovery.dat')) then begin  // Sciher
stellen, dass nicht schreibgeschützt, ansonsten Attriubute zurücksetzen zum
löschen
 //      Attributes := FileGetAttr(PCHar(tftproot+'\recovery.dat'));
//       if (Attributes AND faReadOnly) = faReadOnly then
        FileSetAttr(tftproot+'\recovery.dat', 0);// alle attribute
zurücksetzen//Attributes and not faReadOnly);
       end;
   //     CloseFile(tftproot+'\recovery.dat');
        DeleteFile(tftproot+'\recovery.dat');
     //   showmessage('');
        CopyFile(PChar(ConfigFile),PCHar(tftproot+'\recovery.dat'),False);
       if not FileExists(PCHar(tftproot+'\recovery.dat')) then
        eventlogger('Can''t find file "recovery.dat"', False);
     end
     else begin
      AnList('<recovery> #Copy selected config file to
'+tftproot+'\recovery.dat',True);
     end;
    end;
   end;
end;








Artem Antonov wrote:

> Hello!
>
> The question is: how I can send username and pasword on connection
> with Telnet server without printing them on console, i.e. somethink
> like script?
>
> Thanks.
>
> Best regards,
> Artem Antonov.
> -- 
> To unsubscribe or change your settings for TWSocket mailing list
> please goto http://www.elists.org/mailman/listinfo/twsocket
> Visit our website at http://www.overbyte.be


-- 
To unsubscribe or change your settings for TWSocket mailing list
please goto http://www.elists.org/mailman/listinfo/twsocket
Visit our website at http://www.overbyte.be

Reply via email to