Je fais du support et de la validation, et je suis amené a refaire souvent les même commandes sur des équipements en telnet.
Après avoir cherché comment automatiser telnet avec Autoit, je vous présente mes résultats:
Tout d'abord, je n'utilise pas le client telnet de microsoft car il y a des problèmes pour récupérer la sortie standard. Mais si quelqu'un a réussi proprement je suis preneur.
J'utilise donc plink.exe, (qui est en fait putty en ligne de commande, ), que vous pouvez trouver ici: http://the.earth.li/~sgtatham/putty/lat ... /plink.exe
plink.exe est a placer au même endroit que le script.
Faire de l'automatisation de telnet pour moi c'est :
créer la connexion a l'équipement en utilisant Run plink.exe IP
Envoyer une commande, et attendre un prompt ou une certaine chaine de caractère, pendant un certain temps, en loguant ou pas le contenu.
J'ai donc créé une fonction 'sendExpect' qui envoie une chaine de caractères, et qui en attend une autre.
► Afficher le texte
Code : Tout sélectionner
#include <File.au3>
#include <Constants.au3>
Global $version = '1.00' ; the script version
Global $debug = 0 ; to write all 'print' commands in the html logfile.
Global $expectOutBuffer ; to get the buffer content of sendExpect function, and use it in the script with regexp functions for example
Global $Paused
HotKeySet("{PAUSE}", "TogglePause")
HotKeySet("{ESC}", "Terminate")
Global $exitFunction = 0
HotKeySet("^c", "exitFunction")
Func main()
print("######################################################<br><br>", 'log')
print(@ScriptName & " starts.", 'log')
$ipAddress = "1.2.3.4"
;- Verify if plink is present
If FileExists(@ScriptDir & '\plink.exe') = 0 Then
MsgBox(16, "LogRead. v" & $version, "Unable to find '" & @ScriptDir & "\plink.exe' application." & @CRLF & "Please copy plink.exe at the same location.")
Exit
EndIf
;- Open plink on equipment
print("Open telnet connection on equipment.", 'log')
$telnet_pid = Run(@ScriptDir & '\plink.exe -telnet ' & $ipAddress & ' ', @ScriptDir, @SW_HIDE, $STDIN_CHILD + $STDERR_CHILD + $STDOUT_CHILD)
print('Run : "plink -telnet ' & $ipAddress & '" :' & $telnet_pid & @CRLF)
print('$telnet_pid : ' & $telnet_pid & @CRLF)
;- Create log file. file name is date-hour-ip.log
$printName = @YEAR & @MON & @MDAY & '-' & @HOUR & @MIN & @SEC & '-' & $ipAddress & '.log'
$file = FileOpen(@ScriptDir & '\' & $printName, 2)
;- Log on equipment
print("Connection to equipment.", 'log')
; Send nothing to telnet, but expect 'login' prompt, command and result are written in $file, if we don't find 'login' after '3' seconds, we return -1 and log the error message 'Unable to connect ...
If sendExpect($telnet_pid, '', 'login', 3, $file, 'Unable to connect equipment : ' & $ipAddress & '' & @CRLF & "Can you test with 'telnet " & $ipAddress & "' in a DOS command ?") < 1 Then Return -1
; Send the login, and expect 'Password' prompt within 3 seconds
If sendExpect($telnet_pid, 'blablalogin', 'Password', 3, $file) < 1 Then Return -1
; Send the password, and expect equipment prompt within 3 seconds
If sendExpect($telnet_pid, 'blablapwd', '$', 3, $file ) < 1 Then Return -1
; Send date command, and expect equipment prompt within 3 seconds
sendExpect($telnet_pid, "date", "$", 3, $file)
; Send date command, and expect equipment prompt within 3 seconds, but the command is not written in $file
sendExpect($telnet_pid, "date", "$", 3)
; Send date command, and expect toto within 3 seconds, it fails
sendExpect($telnet_pid, "date", "toto", 3, $file, 'toto not found')
; Send 'ENTER', and expect prompt to be sure the previous command is finished and we can send the next one.
sendExpect($telnet_pid, " ", "$", 3, $file)
; --- Quit telnet ---
print("Exit telnet.", 'log')
sendExpect($telnet_pid, "exit")
FileClose($file)
Return 1
EndFunc ;==>main
$result = main()
print("End of script. Result:" & $result & " ", 'log')
MsgBox(64, "LogRead.", "Script is finished.(" & $result & ")" & @CRLF & "Traces file is at " & @ScriptDir, 5);
If $result = -1 Then Run("C:\Program Files\Internet Explorer\iexplore.exe " & @ScriptDir & "\logs\log_" & @ScriptName & ".htm")
Exit $result
; #FUNCTION# ;===============================================================================
;
; Name ..........: expect() v1.01
; Description ...: Expect a string after a Run(plink) (same as telnet)
; Return values .: On Success - Returns 1
; On Failure - Returns -1
; Variables .....: $process : the process if of the Run plink command
; $inputText : the command you send to the telnet, it can be empty. If you just want to type 'ENTER'
; $expectedString : the string we are looking for, can be empty
; $timeout : if the $expectedString is not found after $timeout seconds, return -1
; $file : if you want to log the telnet
; $errorMessage : if you want a specific message if function fails
; 23 Jul 2010 : Add exit function hotkey functionality
; ;==========================================================================================
Func exitFunction()
$exitFunction = 1
EndFunc ;==>exitFunction
Func sendExpect($process, $inputText, $expectedString = '', $timeout = 3, $file = '', $errorMessage = '')
print("expSend : '" & $inputText & "'" & @CRLF)
If $inputText <> '' Then
StdinWrite($process, $inputText & @CR)
Sleep(100)
EndIf
If $expectedString <> '' Then
print(" Expect : '" & $expectedString & "', with timeout: " & $timeout & '. ')
$rep_err = ''
$rep_ok = ''
$expectOutBuffer = ''
For $i = 1 To $timeout * 4 ;-- *4 : timeout is in seconds and it sleeps 250ms
$rep_err &= StderrRead($process)
If @error Then
print("@Error : STDERR read: " & @error & @CRLF, 'log')
ExitLoop
EndIf
$prevExpectOutBuffer = $expectOutBuffer
$expectOutBuffer = StdoutRead($process)
If $file <> '' Then FileWrite($file, $expectOutBuffer)
If @error Then
print("@Error : STDOUT read: " & @error & @CRLF, 'log')
ExitLoop
EndIf
If StringInStr($prevExpectOutBuffer & $expectOutBuffer, $expectedString) <> 0 Then
print("Expected string : '" & $expectedString & "' found" & @CRLF)
Return 1
EndIf
If $exitFunction = 1 Then
print("User decides to quit sendExpect function. Send CTRL+C to console. " & @CRLF)
StdinWrite($process, Chr(3)) ; chr(3) is CTRL+C
$exitFunction = 0
Return 1
EndIf
Sleep(250)
Next
print("FAILED, Expected string '" & $expectedString & "' not found " & @CRLF, 'log')
If $file <> '' Then FileWrite($file, $expectOutBuffer)
If $errorMessage <> '' Then MsgBox(16, "ERROR", "Expected string '" & $expectedString & "' not found." & @CRLF & $errorMessage)
Return -1
EndIf
Return 1
EndFunc ;==>sendExpect
; #FUNCTIONS# ;===============================================================================
; Permit to Pause the script
Func TogglePause()
$Paused = Not $Paused
While $Paused
Sleep(100)
ToolTip('Script is "Paused"', 0, 0)
WEnd
ToolTip("")
EndFunc ;==>TogglePause
; Permit to quit the script with ESC
Func Terminate()
Exit 0
EndFunc ;==>Terminate
; #FUNCTION# ;===============================================================================
;
; Name...........: print() v1.01
; Add $text in console
; if $debug=1 or if $log<>'', add $text in a html file (scriptname.html)
; ;==========================================================================================
Func print($text, $log = '')
ConsoleWrite($text)
If $log <> '' Or $debug = 1 Then
If Not FileExists(@ScriptDir & "/logs") Then DirCreate(@ScriptDir & "/logs")
TrayTip("", $text, 1)
_FileWriteLog(@ScriptDir & "/logs/log_" & @ScriptName & ".htm", "<font face=Verdana size=2>" & $text & "</font><br>", 1)
EndIf
EndFunc ;==>print


