Sign in to follow this  
Followers 0
DjTaz

Putty with Console Cable

9 posts in this topic

Hi All,

I downloaded Autoit hoping i could get putty to login into a router and run some commands over a console cable.

Now , from reading around i can see that it should be possible , but i dont think i have the ability to do it myself so im asking for some help.

Basically what i would like is the following

1. Putty.exe to open

2. Select Serial connection on Com1 speed 9600

3. Open Connection

4. Wait until a default configuration router loads

5. Type in a set of commands like 'show ver', 'show run', 'show log'

6. Enter Config mode and make a change to an interface .... 'conf t' then 'interface fe0' and command 'ip address 192.168.1.200 255.255.255.0'

7. Once set do a 'show arp' command or something similar

8. send a reload command and then log out and close putty.

If someone could either give me an idea of how to do this or show me an example or something similar that i could edit to my needs id appreciate it a lot.

Thanks guys.

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Right , so i got so far , but the only real coding i have done is with PHP and mysql so a lot of this stuff is new to me.

I have managed to get putty to log in and use the console cable by making a Console profile on putty and calling that, and its logging in and sending commands (thankfully).

I tried using a sleep command to get the script to wait for the router to boot fully but that doesnt seem to work because it takes a different length of time to load each reboot, so i was trying to get it to wait for a certain prompt and then continue on its way , but im missing something ... any help ?

(Putty profile for my local router is Cisco, so im using that to test)

oShell.Run "C:\putty.exe -load Cisco", 1, FALSE


' Wait for the Putty window to ask for username and enter it
oAutoIt.WinWaitActive "192.168.1.254 - PuTTY", "login as:"
oAutoIt.Send "myusername{Enter}"

' Wait for the Putty window to ask for password and enter it
oAutoIt.WinWaitActive "192.168.1.254 - PuTTY", "Password:"
oAutoIt.Send "mypass{Enter}"

' Wait for the Putty window to show the device name , then show the clock info
oAutoIt.WinWaitActive "192.168.1.254 - PuTTY", "Cisco_rtr#"
oAutoIt.Send"show clock{Enter}"
Edited by DjTaz

Share this post


Link to post
Share on other sites

#3 ·  Posted (edited)

Well i have it all working now, but its not at all neat or technically correct as its just based on pauses and snd commands, btu at least it works.... if anyone could help me make it more reliable id appreciate it.

I have a profile set up on putty called serial which selects the com port and speed of 9600.

Option Explicit 
Dim oShell
Dim oAutoIt


Set oShell = WScript.CreateObject("WScript.Shell")
Set oAutoIt = WScript.CreateObject("AutoItX3.Control")

' Open the putty Window and run the script
oShell.Run "putty.exe -load serial", 1, FALSE


' Wait for the Putty window to become active
oAutoIt.WinWaitActive "COM1 - PuTTY", ""

' Make a loop forever
While 1
oAutoIt.Sleep 120000

' Pres Enter and wait until the Username is there
oAutoIt.Send"{Enter}"
oAutoIt.Sleep 5000

' Enter The username and password and pause
oAutoit.WinWaitActive(
oAutoIt.Send"cisco{Enter}"
oAutoIt.Sleep 2000
oAutoIt.Send"cisco{Enter}"
oAutoIt.Sleep 2000
oAutoIt.Send"cisco{Enter}"
oAutoIt.Sleep 2000

' Erase the existing config the router comes with
oAutoIt.Send"write erase{Enter}"
oAutoIt.Send"{Enter}"
oAutoIt.Sleep 1000

' Reload the router with the erased config 
oAutoIt.Send"reload{Enter}"
oAutoIt.Sleep 1000
oAutoIt.Send"no{Enter}"
oAutoIt.Sleep 1000 
oAutoIt.Send"{Enter}"
oAutoIt.Sleep 1000

' Sleep until the router comes back up - then answer no to the Initial Dialogue question
oAutoIt.Sleep 120000
oAutoIt.Send"no{Enter}"
oAutoIt.Sleep 3000
oAutoIt.Send"{Enter}"
oAutoIt.Sleep 10000

' Enter in the Basic Config 
oAutoIt.Send"en{Enter}"
oAutoIt.Sleep 2000
oAutoIt.Send"conf t{Enter}"
oAutoIt.Sleep 6000
oAutoIt.Send"!{Enter}"
oAutoIt.Sleep 1000
oAutoIt.Send"hostname Basic{Enter}"
oAutoIt.Sleep 1000
oAutoIt.Send"enable password password{Enter}"
oAutoIt.Sleep 1000
oAutoIt.Send"interface ATM0{Enter}"
oAutoIt.Sleep 1000
oAutoIt.Send" no ip address{Enter}"
oAutoIt.Sleep 1000
oAutoIt.Send" no atm ilmi-keepalive{Enter}"
oAutoIt.Sleep 1000
'blah
'blah
'blah
'blah
'blah
'blah
'blah
'blah
'blah
'blah
'blah
'blah

'End the Loop 
WEnd
Edited by DjTaz

Share this post


Link to post
Share on other sites

I'm a bit late to reply, but better now than never. I was instructed to check out Plink for my cisco switch scripting. I have just begun last month modding some of my scripts from use with Putty to plink, but i haven't had time to finish and test. I currently have no scripts to share on this matter, but take that advice for what it is. I love Putty, but for scripting I would have to agree that Plink is the way to go. I can't understand why you are working with serial connections only. I do know that my script is faulted with referencing Telnet upon SSH failure or SSH upon Telnet failure, but I had my reasons when I started walking down that path. The reason for that was because many switches had different passwords and some were Telnet disabled and SSH only.

I'm not 100% familiar with VB script, but I see what you are doing. I might have a little difficulty with working in VBS, but I'm willing to help with time.

The way I did it initially was:

Verify required programs are present and direct the user to them if not via web browser.

Start Putty

Select Mode

Set logging option

Initiate communication with switch

Log into switch

Wait for login success, error out upon failure and move to next switch in queue (May attempt to initiate alternative login, faulted logic)

Run selected tasks (backup config, set reload time, set ntp, etc.)

# Many of the selected tasks parsed the logs to verify completion or waited for keywords to indicate when to move on

Send any generic commands from user placed in text area.

Post to user a summary of events performed for each switch then move on to next switch in queue.

I think everything you want to do can be done by modding my script to work with serial connections. You simply have to disable the fallback from one mode to another, which I can help with since it is my faulted logic that placed it there. Then change the window detection from the current IP to one that matches Putty's serial connection window information. From what it sounds you don't have any type of login requirements and therefore will not be needing that so that part can be removed as well so that there is no holdup in waiting for response to verify properly logged in.

Share this post


Link to post
Share on other sites

I'm a bit late to reply, but better now than never. I was instructed to check out Plink for my cisco switch scripting.

Hey Man, thanks for the reply, i appreciate it.

The thing is , i have Linux scripts running that are all capable of logging into the routers and doing everything once they have a connection of any kind.

The thing that stumped me was getting a basic configuration onto a router (I work with routers, not switches) out of the box which is why i needed a serial cable.

I can get the script to log into the box over serial , then write erase the default config , and write on a basic config i need.

What i have seems to work ok , but it is all based on sleep timers and loops and it would be so much easier if it only replied to expected prompts.

Im not great at autoit so i was using VB since it was simple and suited what i wanted to do.

Again , thanks for the reply, and if you can be of assistance , or anyone else , it would be amazing.

Share this post


Link to post
Share on other sites

Are you using the Putty application? If you are using VB script I really can't help since that isn't my preferred scripting language.

In my script there is two functions that could be a huge help. One is the login function, which you can modify to select Serial instead of Telnet or SSH. The second is the parsing of the log for expected keywords. See below.

Login:

Func startPuttySsh()
    Run("C:\Program Files\PuTTY\putty.exe")
    WinWait("PuTTY Configuration")
    If Not WinActive("PuTTY Configuration") Then WinActivate("PuTTY Configuration")
    WinWaitActive("PuTTY Configuration")
    Send($sIpAddress) ;port 22 automatically selected
    Send("!s") ;select SSh
    Send("+{TAB 3}")
    Sleep(250)
    Send("{DOWN}") ;enter logging options window
    ControlSend("PuTTY Configuration", "Log &file name:", "Edit1", "{DEL 10}")
    ;ControlSetText("PuTTY Configuration", "Log &file name:", "Edit1", $sPuttyLogFileLocation & "\Putty.log") ;disabled for workaround
    ControlSetText("PuTTY Configuration", "Log &file name:", "Edit1", $sTempPuttyFileLocation & "\Putty.log")
    If Not WinActive("PuTTY Configuration") Then WinActivate("PuTTY Configuration")
    WinWaitActive("PuTTY Configuration")
    ;select printable output
    Send("!p")
    If Not WinActive("PuTTY Configuration") Then WinActivate("PuTTY Configuration")
    WinWaitActive("PuTTY Configuration")
    ;select always overwrite existing log
    Send("!e{UP 3}")
    ;delete existing logfile to prevent handling leftover logfile from previous sessions masking problems
    If FileExists($sPuttyLogFileLocation & "\Putty.log") Then
        FileDelete($sPuttyLogFileLocation & "\Putty.log")
        FileDelete($sTempPuttyFileLocation & "\Putty.log") ;temporary workaround
    EndIf
    If Not WinActive("PuTTY Configuration") Then WinActivate("PuTTY Configuration")
    WinWaitActive("PuTTY Configuration")
    ControlClick("PuTTY Configuration", "&Open", "Button1")
    If WinWait("PuTTY Security Alert", "The server's host key is not cached", 5) Then
        If Not WinActive("PuTTY Security Alert") Then WinActivate("PuTTY Security Alert")
        WinWaitActive("PuTTY Security Alert")
        ControlClick("PuTTY Security Alert", "&Yes", "Button1")
    EndIf
EndFunc

Parsing the log:

Func parseLogFileSingleKeyword($sFileToSearch, $sKeyword)
    Local $bReturnFlag = False
    FileCopy($sTempPuttyFileLocation & "\Putty.log", $sPuttyLogFileLocation & "\Putty.log", 1) ;workaround
    ;analyze logfile created to parse for single keyword
    $logfile = FileOpen(String($sFileToSearch), 0)
    ; Check if file opened for reading OK
    If $logfile = -1 Then
        postNotification("Unable to open " & $sFileToSearch & " for single keyword parse.", 1, 1, 1)
        MsgBox(48, "Error", "Unable to open " & $sFileToSearch & " for single keyword parse.")
        Exit
    EndIf
    ; Read in lines of text until the EOF is reached
    While 1
        $line = FileReadLine($logfile)
        If @error = -1 Then ExitLoop
        If StringInStr($line, $sKeyword) Then
            ;switch is responding
            $bReturnFlag = True
        EndIf
    WEnd;end reading file
    FileClose($logfile)
    Sleep(2000) ;release resources
    Return $bReturnFlag
EndFunc

To hold the script at a location to wait for a specific word to show up then use this:

While Not parseLogFileSingleKeyword($logPath, $stringToWaitFor)
   ;Loop of sleep or actions to do while waiting
   Sleep(500)
WEnd
; After the expected word in the logs shows up then the script continues.

My attempt to find the reasoning behind the need for my workaround if curious.

Share this post


Link to post
Share on other sites

[autoit][/autoit]Hi All,

First time actually posting, well...anything :)

Anyways here goes:

I too work with routers and switches mostly Cisco but also some extremes and hp switches... I had need to gather configs and NAC related info from all of the devices. So, this is what I came up with to pull down the config. It is only part of a bigger project that I thought would give you some alternative ideas. This is a TCP connection but I will be building a seperate function for a serial/com port connection and using direct send/recv communication. I do not take credit for all the ideas in this script. I the many resources and examples found on this site and posted from other users.

Global $packet, $rdata, $sdata, $ip, $socket, $port, $eSect, $hname, $sTitle, $fTitle
;This line appears in the data stream, So I remove it at the end from the log file created.
$eSect = "          "
TCPStartup()
Dim $uname, $rHost
;Get the IP address of the router
;;;;$ip = InputBox("IP Address", "Please enter the IP address.", "192.168.1.10", "",190, 115)
;;;;If @error = 1 Then Exit

;-------------------------------------------------
;For Future use...Converts name to IP address
;example: $ip = TCPNameToIP("server.company.com")
;-------------------------------------------------

$port = "23"
$data = -1
$uname = "yourusername" ;can be change to an input box

;Function that opens TCP(Telnet) connection to router, and
;Uses TCPRecv and TCPSend to send Username and Password to log into router.
Func Rtr_Connect()
    $socket = TCPConnect($ip, $port) ;Setup connection and main socket is created
    While StringInStr($rdata, "#") = 0 ;Continue loop until login has completed
        If $socket = -1 Then ; Error out if connection fails
            MsgBox(0, "No Data", "No Data see--->" & $data & @CR _
                     & "Socket Status--->" & $socket & @CR _
                     & "Packet Sent---->" & $packet)
            Exit
        EndIf
        $rdata = TCPRecv($socket, 4096) ;Data in socket is sent to variable as string
        If StringInStr($rdata, "Username") Then ;Looks for "Username" when data has been received
            TCPSend($socket, $uname) ;Sends username
            TCPSend($socket, @CRLF)
            Do                                    ;Loop created until the "Password is detected.
                Sleep(100)
                $rdata = TCPRecv($socket, 4096)
            Until StringInStr($rdata, "Password") ;Send Password when password request is received
            Sleep(100)
            TCPSend($socket, "yourpassword") ;Sends password
            TCPSend($socket, @CRLF)
            Sleep(100)
            While StringInStr($rdata, "#") = 0 ;This loop is used to detedct the # sign which indicates a successful logon.
                $rdata = TCPRecv($socket, 5000)
                If StringInStr($rdata, "#") Then ;This will pull out the hostname of the router.
                    $hname = StringRight($rdata, (StringLen($rdata) - StringInStr($rdata, " ", 0, 0, -1)))
                    $hname = StringReplace($hname, @CRLF, "")
                    $hname = StringReplace($hname, "#", "")
                    MsgBox(1, "Login Successful", "You have logged in successfully to " & @LF & @LF & "**   " & $hname & "  **")
                EndIf
            WEnd
        EndIf
    WEnd
EndFunc

Func Show_Run()
    Dim $showrun
    Dim $aMB

    $fTitle = "*****************************************************************"
    $sTitle = "**** Show Run Report on Host " & $hname & " - " & $ip & "    ****"

    TCPSend($socket, "show run" & @CRLF); Send the show run command to the router
    Sleep(3000)
    $rdata = TCPRecv($socket, 4000)
    $showrun = $rdata
    If StringInStr($rdata, "--More--") Then ;If the --More-- string is detect begin loop
        Do ;Loop will fill the variable until no --More-- is detected
            TCPSend($socket, " ")
            Sleep(500)
            $rdata = TCPRecv($socket, 5000)
            $showrun = $showrun & $rdata
        Until StringInStr($rdata, "--More--") = 0
        $showrun = StringReplace($showrun, "--More--", "", 0) ;trip out the text from string
        Sleep(10)
        $showrun = StringReplace($showrun, $eSect, "", 0) ;Strips out another string
    EndIf
    Sleep(50)
    ;Create or Open a text file and insert the string
    _FileWriteLog("c:\LogFile.txt", @CRLF & @CRLF & $fTitle & @CRLF & $sTitle & @CRLF & $fTitle & @CRLF & @CRLF & $showrun)
    $aMB = MsgBox(4, "Show Run", "Your request has been completed." & @CRLF & "A log file" _
             & "has been created here:" & @LF & @LF & "c:\LogFile.txt")
    If $aMB = 6 Then
        Run("notepad.exe c:\LogFile.txt")
    
EndIf

This is just a part of the project but can give you an idea of what I intended to accomplish.

Dont forget your Includes... at the top of your project.

I will work on the serial connection this weekend and update as I get further.

Does anyone know of a good ssh library/com that autoit has or can use (call to vb/c++ component) to connect to an ssh server and that I can then send and recv messages through the channel? I have done a bit of reading and coming up short with autoit's ability for secure shell. I feel I may have to go back to vb.net to complete this project.

So, I hope my first post was not to newbeish.

Share this post


Link to post
Share on other sites

Hi,

I am a newbie to AutoIt. I need to read  a specific text (23digit alphanumeric) from putty window. (if not possible, then from log file). I have jotted down my scenario here.

1. Open Putty

2. Config Ip, port.

3. Connect login

4. Navigate to ABC folder

5. type <ls -lrt>

6. In the list of files, take the latest one.

Sample file entry <Mar 23 14 some text some value 12345abcde67890fhijk999>

7. cd 12345abcde67890fhijk999

I need to get the "12345abcde67890fhijk999". Is this possible in AutoIt? If yes, what kind of function I should use/create. Please help me out.

 

Share this post


Link to post
Share on other sites

#9 ·  Posted (edited)

The log one would be easy, and someone can probably craft a quality regexp to handle any parsing; i will be able to give you a functional, yet terrible, regexp.   I would start a new thread, posting exactly what the file contains, and exactly what you like to parse from the contents.  The result will be file and string operations, moreso than help with putty, so it probably is not best suited for this 3 year old thread.

Edited by boththose

,-. .--. ________ .-. .-. ,---. ,-. .-. .-. .-.
|(| / /\ \ |\ /| |__ __||| | | || .-' | |/ / \ \_/ )/
(_) / /__\ \ |(\ / | )| | | `-' | | `-. | | / __ \ (_)
| | | __ | (_)\/ | (_) | | .-. | | .-' | | \ |__| ) (
| | | | |)| | \ / | | | | | |)| | `--. | |) \ | |
`-' |_| (_) | |\/| | `-' /( (_)/( __.' |((_)-' /(_|
'-' '-' (__) (__) (_) (__)

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  
Followers 0