Jump to content
Sign in to follow this  
Jason86

Putty commands through AutoIT

Recommended Posts

Jason86

Hi,

I would like to automate Putty commands whereby it will select my saved telnet session (so open Putty Configuration and select session) and afterwards it will open the Putty-prompt and will do next commands:

<Enter>
ACCESS <Enter>
'UserName' <Enter>
SET Priv <Enter>
'Password' <Enter>
LOG PORT ALL <Enter>

And close Putty

Kind of new in AutoIT so all help is welcome !

 

Thanks in advance,

Regards,

 

Share this post


Link to post
Share on other sites
SlackerAl

You might want to check out plink.exe (command line putty) which works better for non-interactive telnet operations and can be run from a batch file.

  • Like 1

Problem solving step 1: Write a simple, self-contained, running, replicator of your problem.

Share this post


Link to post
Share on other sites
JLogan3o13

Agree that plink is probably your best bet. I do a lot in putty sessions for customers, and use the following as a framework:

Local $sEXE = @MyDocumentsDir & "\PuTTY\PLINK.EXE"
Local $sUser = " -l root"
Local $sPass = " -pw Password1"
Local $sCommand = " esxcli storage vmfs unmap -l "

    For ...
        ShellExecute($sEXE, " -ssh " & $aRange1[$a][1] & $sUser & $sPass & $sCommand & $aRange1[$a][0]) ; - Pulls datastores from excel range and runs vmfs unmap
    Next

 

  • Like 1

√-1 2^3 ∑ π, and it was delicious!

Share this post


Link to post
Share on other sites
SlackerAl

Depending on your circumstances you may also want to look at using ssh keys rather than embedding your username/password (care where you put the private key!).


Problem solving step 1: Write a simple, self-contained, running, replicator of your problem.

Share this post


Link to post
Share on other sites
Jason86
36 minutes ago, SlackerAl said:

You might want to check out plink.exe (command line putty) which works better for non-interactive telnet operations and can be run from a batch file.

so something like : putty.exe -load “session name” but how to start this session and run the commands ? :s

Share this post


Link to post
Share on other sites
Jason86
13 minutes ago, SlackerAl said:

:D Thanks SlackerAl , I found this on the net:


\path\to\putty.exe -load "[Sessionname]" -l [user] -pw [password] -m C:\path\to\commands.txt

 

and in commands.txt I'll put the commands mentioned here beneath :

<Enter>
ACCESS <Enter>
'UserName' <Enter>
SET Priv <Enter>
'Password' <Enter>
LOG PORT ALL <Enter>

Thanks !

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  

  • Similar Content

    • nill
      By nill
      $user = "root" $password ="" $host ="5.0.0.1" $port ="22" $puty_exe = @ScriptDir & "\putty.exe"; putty salve local folder script $command = Run(@comspec & " /C "&$puty_exe&" -ssh -l "&$user&" "&$host&" p "&$port&" -pw "&$password,@ScriptDir, @SW_HIDE, 1) While 1 $data = StdoutRead($command) ConsoleWrite($data&@CRLF) If @error Then ExitLoop Wend Why StdoutRead cant read what putty.exe write in console ?
    • JiBe
      By JiBe
        Hi to all,
       
       
      I only am accustomed pas has posted on the forum (coz, I'm french). But I use it a lot.
      So first of all, thank you all to participate in the evolution of this wonderful product.
      Today is not one day like any other, I myself am decide has posted a UDF that I myself create and developed (there may be some bug) for some months.
      So here it is:
      This UDF allows to use the SSH protocol very easily in your code.
      It uses the syntax as the TCPxxx() function.
      Your code will be easier to convert :-).
       
      excused my English, I'm French.
       
      Example:
       
      #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.4.0 Author: Joseph Barone 2010-2015 Script Function: Modele pour l'utilisation de la fonction ssh (plink). #ce ---------------------------------------------------------------------------- ; Script Start - Add your code below here #include #include #include #include #include #include "SSH_udf.au3" _SSHStartup() Global $butt[6] $Gui = GUICreate("SSH Console",550,400) $label1 = GUICtrlCreateLabel("Adresse IP:",10,10,150,20) ; ip $input1 = GUICtrlCreateInput("",10,25,150,20) ; ip $label2 = GUICtrlCreateLabel("Tcp port:",170,10,150,20) ; port $input2 = GUICtrlCreateInput("",170,25,60,20) ; port $label6 = GUICtrlCreateLabel("Protocol:",240,10,40,20) ; port $input6 = GUICtrlCreateInput("ssh",240,25,60,20) ; port $butt[0] = GUICtrlCreateButton("Connect0",310,5,80,20,$BS_DEFPUSHBUTTON) $butt[1] = GUICtrlCreateButton("Connect1",390,5,80,20) $butt[2] = GUICtrlCreateButton("Connect2",470,5,80,20) $butt[3] = GUICtrlCreateButton("Connect3",310,25,80,20) $butt[4] = GUICtrlCreateButton("Connect4",390,25,80,20) $butt[5] = GUICtrlCreateButton("Connect5",470,25,80,20) $Checkbox = GUICtrlCreateCheckbox("RSA, Fingerprint, Alert AutoValidate", 330, 45, 205, 25) $label4 = GUICtrlCreateLabel("Login:",10,45,150,20) ; login $input4 = GUICtrlCreateInput("",10,60,150,20) ; login $label5 = GUICtrlCreateLabel("Mot de passe:",170,45,150,20) ; password $input5 = GUICtrlCreateInput("",170,60,150,20,$ES_PASSWORD) ; password $label3 = GUICtrlCreateLabel("Commande a envoyer:",10,85,150,20) ; send command $input3 = GUICtrlCreateInput("",10,100,310,20) ; send commande vers l'hote $butt2 = GUICtrlCreateButton("Send",330,100,80,20,$BS_DEFPUSHBUTTON) GUICtrlSetState($butt2,$GUI_DISABLE) $edit = GUICtrlCreateEdit("",10,130,530,260,$WS_VSCROLL);,$WS_DISABLED)) GUISetState() Global $ConnectedSocket[6] = [-1,-1,-1,-1,-1,-1] Global $msg, $recv, $ret ; GUI Message Loop ;============================================== While 1 $nmsg = GUIGetMsg() If $nmsg = $GUI_EVENT_CLOSE Then ExitLoop ;;; connect part: $b = 0 While 1 If $nMsg = $butt[$b] Then If GUICtrlRead($butt[$b]) = "Connect"&$b Then _SSHParametreSet("yesall",GUICtrlRead($Checkbox)) _SSHParametreSet("protocol",GUICtrlRead($input6)) _SSHParametreSet("login",GUICtrlRead($input4)) _SSHParametreSet("passwd",GUICtrlRead($input5)) $ConnectedSocket[$b] = _SSHConnect(GUICtrlRead($input1),GUICtrlRead($input2)) If $ConnectedSocket[$b] = 0 Then MsgBox(0,"Erreur", "Impossible de ce connecter!!") Else GUICtrlSetData($butt[$b],"Close"&$b GUICtrlSetState($butt2,$GUI_ENABLE) EndIf DisplayArray($_config) ConsoleWrite("nb config:"&$_nbconf&@CRLF) Else _SSHCloseSocket($ConnectedSocket[$b]) GUICtrlSetData($butt[$b],"Connect"&$b GUICtrlSetState($butt2,$GUI_DISABLE) DisplayArray($_config) ConsoleWrite("nb config:"&$_nbconf&@CRLF) EndIf EndIf ;;; send part: If $nMsg = $butt2 Then $ret = _SSHSend( $ConnectedSocket[$b] , GUICtrlRead($input3)&@crlf) GUICtrlSetData($input3,"") GUICtrlSetState($input3,$GUI_FOCUS) EndIf ;;; receive part: $recv = _SSHRecv( $ConnectedSocket[$b]) If $recv <> "" Then GUICtrlSetData($edit, GUICtrlRead($edit) & $recv ) EndIf GUICtrlSendMsg($edit, $EM_SCROLL, $SB_PAGEDOWN, 0) $b += 1 If $b = UBound($butt) Then ExitLoop WEnd WEnd _SSHCloseSocket($ConnectedSocket) _SSHShutdown() Exit Func DisplayArray($array) $i = 0 $j = 0 if UBound($array,1) = 0 Then Return While 1 ConsoleWrite("(["&UBound($array,1)&"]["&UBound($array,2)&"]) ") While 1 ConsoleWrite("["&$j&"]"&$array[$i][$j]&" ") $j += 1 if UBound($array,2)<=$j Then ExitLoop WEnd ConsoleWrite(@CRLF) $i += 1 $j = 0 if UBound($array,1)<=$i Then ExitLoop WEnd EndFunc   
      I join with UDF version of modified putty myself.  :-) LoL
      but, it is not used with the UDF, it is included in the UDF.
       
      putty-04012015- 92453+lic.zip
      ssh_udf.zip
    • taylansan
      By taylansan
      Dear Autoit Forum,
      Before I start, I have checked the following topics, but couldn't get far enough:
      '?do=embed' frameborder='0' data-embedContent>>

      Func _PLINK_Connect($remote, $user, $password) Local $hSessionPID = Run("plink.exe -ssh " & $remote & " -l " & $user & " -pw " & $password, "", @SW_HIDE, $STDIN_CHILD + $STDOUT_CHILD) If @error Then MsgBox(0, "Error: xxx", "Running plink.exe under the main folder failed.") Return False EndIf Local $sLine While True ;read each line $sLine = StdoutRead($hSessionPID) ;ty_DEBUG print each line after connected If $sLine <> "" Then ConsoleWrite("Current Line Start:" & $sLine & @CRLF & "==== Current Line End" & @CRLF) If ProcessExists($hSessionPID) = 0 Then ConsoleWrite("cannot find PID" & @CRLF) Return SetError(9) ;check if connected with the given user name ElseIf StringInStr($sLine, "Using keyboard") Then ConsoleWrite("cannot login" & @CRLF) Return SetError(8) ;check if connected to remote ElseIf StringInStr($sLine, " [cdr2db] :") Then ConsoleWrite("connected to remote" & @CRLF) ExitLoop EndIf Sleep(10) WEnd Return $hSessionPID EndFunc Now i call the function:
      Case1: Everything is fine
      _PLINK_Connect("10.25.0.20", "cdr2db", "Cdr2db_1")
      Output:
      Current Line Start:Last login: Sat Sep 13 12:56:06 2014 from 10.75.58.71


      ==== Current Line End
      Current Line Start:<101 bb1a [cdr2db] :/onip/app/cdr2db>
      ==== Current Line End
      connected to remote

      Case2: Another username
      _PLINK_Connect("10.25.0.20", "cdr2dba", "Cdr2db_1")
      Output:
      Current Line Start:Using keyboard-interactive authentication.
      Password:
      ==== Current Line End
      cannot login
      Using username "cdr2dba".
      Access denied

      Case3: Wrong password
      _PLINK_Connect("10.25.0.20", "cdr2db", "Cdr2db_1a")
      Output:
      Current Line Start:Using keyboard-interactive authentication.
      Password:
      ==== Current Line End
      cannot login
      Using username "cdr2db".
      Access denied

      Case4: Non-existing remote machine
      Output:
      FATAL ERROR: Network error: Connection timed out
      cannot find PID
      Now my question is that:
      For Case 2 and 3; my last console write says that "current line start / end" then, "cannot login". But in the output window i can find "Using username cdr2db. Access denied". So, how is that output generated?
      For Case 4: Even there is no output as ConsoleWrite, how the "FATAL ERROR: ..." line is generated?
      I would apperiate any comments on the topic.
      Thanks in advance.
    • Yaerox
      By Yaerox
      Hey guys,   I want to use Putty/Plink to connect on a remote computer via SSH because I need to execute a couple commands there. So I researched a couple days now and tried like 20 different ways to get this running but I'm still failing. Maybe a little description what my script should do:   #Edit: Short version: I need to use StdoutRead to get the DOS command promt output MORE THAN ONCE! The first time is working, but I need to get this the whole time till I say stop ^^   I want to start Putty/Plink and connect via SSH on a remote computer AND I wanna check if there is anything wrong going on or not, because the next step would be the execution of an perl-script on the remote computer which is giving an output text while running. That means I'd like to be able to read out the Putty-Window/Plink-Console the whole time ... I'm actual just getting the text-output after connecting.   Maybe a little example of what I'm expecting in some kind of mixed "AutoIt/Pseudo -Code":   #include <Constants.au3> Local $iPID = Run('"C:\Program Files (x86)\Putty\putty.exe" -ssh root@HOST:22 -pw PASSWORD', @ScriptDir, @SW_SHOW, $STDERR_CHILD + $STDOUT_CHILD)   Actual Putty-Window is popping up showing me: Using username "root". Linux COMPUTERNAME 2.6.31-22-generic-pae #63-Ubuntu SMP Wed Aug 18 23:57:18 UTC 2010 i686   To access official Ubuntu documentation, please visit: http://help.ubuntu.com/     System information as of Mo 13. Jan 15:01:50 CET 2014     System load:  0.0               Processes:           77   Usage of /:   47.5% of 9.15GB   Users logged in:     1   Memory usage: 9%                IP address for eth2: HOST   Swap usage:   0%     Graph this data and manage this system at https://landscape.canonical.com/   Last login: Mon Jan 13 14:58:43 2014 from XXX.X.X.XXX root@COMPUTERNAME:~#   Now I'd like to do ControlSend($hWindow_Putty, '', '', 'perl -w /some/dir/script.pl{ENTER}')   If I'd do this on my on with Putty I'd now see something like:   Using username "root". Linux COMPUTERNAME 2.6.31-22-generic-pae #63-Ubuntu SMP Wed Aug 18 23:57:18 UTC 2010 i686   To access official Ubuntu documentation, please visit: http://help.ubuntu.com/     System information as of Mo 13. Jan 15:01:50 CET 2014     System load:  0.0               Processes:           77   Usage of /:   47.5% of 9.15GB   Users logged in:     1   Memory usage: 9%                IP address for eth2: HOST   Swap usage:   0%     Graph this data and manage this system at https://landscape.canonical.com/   Last login: Mon Jan 13 14:58:43 2014 from XXX.X.X.XXX root@COMPUTERNAME:~# perl -w some/dir/script.pl some text written by the script.pl some text written by the script.pl some text written by the script.pl root@COMPUTERNAME:~#   And that's what my problem is. I need to be able to check this output of the script like "some text written by the script.pl" because I may not execute a following statement if this one didn't succeed. In my thoughts the first step should show me what I got in the first code-box above, and the second output should be perl -w some/dir/script.pl some text written by the script.pl some text written by the script.pl some text written by the script.pl root@COMPUTERNAME:~# but I dont get this working ...   So I found many threads about Plink. I tried the whole thing with Plink...   Local $sData = '' Local $iPID = Run('"C:\Program Files (x86)\Putty\plink.exe" -ssh root@HOST:22 -pw PASSWORD', @ScriptDir, @SW_SHOW, $STDERR_CHILD + $STDOUT_CHILD)   While True     $sData &= StdoutRead($iPID)     If @error Then ExitLoop     Sleep(25) WEnd   ConsoleWrite("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" & @CR & _ $sData & @CR & _ "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" & @CR)  I'm getting the following output: Linux COMPUTERNAME 2.6.31-22-generic-pae #63-Ubuntu SMP Wed Aug 18 23:57:18 UTC 2010 i686   To access official Ubuntu documentation, please visit: http://help.ubuntu.com/     System information as of Mo 13. Jan 15:35:53 CET 2014     System load:  0.0               Processes:           77   Usage of /:   47.5% of 9.15GB   Users logged in:     1   Memory usage: 9%                IP address for eth2: HOST   Swap usage:   0%     Graph this data and manage this system at https://landscape.canonical.com/   Last login: Mon Jan 13 15:23:36 2014 from MY_IP_ADRESS   In comparison to the Putty window-output I'm missing here the  root@COMPUTERNAME:~# line ... anyway, I don't get this Plink thing doing more then just connecting ... no more executions I'm getting done ...   I also tried something like: #RequireAdmin #include <Constants.au3>   Local $sData = '' Local $iPID = ShellExecute(@ComSpec, '"C:\Program Files (x86)\Putty\plink.exe" -ssh root@HOST:22 -pw PASSWORD', @ScriptDir, '', @SW_SHOW)   Local $hWindow = WinWait('Administrator: C:\Windows\system32\cmd.exe', '', 5) ConsoleWrite("WinWait: " & $hWindow & @CR) If $hWindow = 0 Then Exit ConsoleWrite("WinActivate: " & WinActivate('Administrator: C:\Windows\system32\cmd.exe') & @CR) ConsoleWrite("WinActive: " & WinActive('Administrator: C:\Windows\system32\cmd.exe') & @CR)   Sleep(1000) ConsoleWrite(ControlSend('Administrator: C:\Windows\system32\cmd.exe', '', '', '"C:\Program Files (x86)\Putty\plink.exe" -ssh root@HOST:22 -pw PASSWORD{ENTER}') & @CR)   ;StdinWrite($iPID, '"C:\Program Files (x86)\Putty\plink.exe" -ssh root@HOST:22 -pw PASSWORD' & @CRLF) ;StdinWrite($iPID)   While True     $sData &= StdoutRead($iPID)     If @error Then ExitLoop     Sleep(25) WEnd   ConsoleWrite("~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" & @CR & _ $sData & @CR & _ "~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~" & @CR) but unfortunately I dont get anything out of it ...   Maybe a last more example ... I found this on Stackoverflow (http://stackoverflow.com/questions/19206834/command-prompt-and-autoit-stdinwrite) Thats my code after reading that article: #include <Constants.au3>   Local $data Local $pid = Run("C:\Windows\system32\cmd.exe",@SystemDir, @SW_HIDE, $STDIN_CHILD + $STDOUT_CHILD) StdinWrite($pid,"cd C:\users\username") StdinWrite($pid,@CRLF) ;~ StdinWrite($pid)   Sleep(2000)   $data &= StdoutRead($pid) ConsoleWrite("Debug:" & $data & @LF)   $data = ''   StdinWrite($pid,"cd C:\Program Files (x86)") StdinWrite($pid,@CRLF) StdinWrite($pid)   $data &= StdoutRead($pid) ConsoleWrite("Debug:" & $data & @LF) but the second output still empty...   Can you guys please help me out? Thanks in advice. Regards.
    • JRSmile
      By JRSmile
      This Function gets the Hostname of the Client on the Terminal Server,
      can be used to determine the correct std printer near the location of the client while working on the terminal server session.


      Func _GetWTSClientName($sid) Local $result = DllCall("Wtsapi32.dll", "int", "WTSQuerySessionInformation", "Ptr", 0, "int", $sid, "int", 10, "ptr*", 0, "dword*", 0) If @error Or $result[0] = 0 Then Return SetError(1, 0, "") Local $ip = DllStructGetData(DllStructCreate("byte[" & $result[5] & "]", $result[4]), 1) DllCall("Wtsapi32.dll", "int", "WTSFreeMemory", "ptr", $result[4]) Return StringReplace(BinaryToString($ip), Chr(0), "") EndFunc ;==>_GetWTSClientName
      Best regards,
      J
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.