Jump to content
stev379

How can I turn text from a cmd prompt into a variable that I can split?

Recommended Posts

Please don't give me the entire answer. I'd like to figure out as much on my own as i can, but need some nudging in the right direction.

I've compiled the example script and I see how it works, but haven't figured out how to get my entire idea going.

I need to run nslookup on multiple machines a few times each year and I'm using an input field to test with so others here could use the finished tool as well. Ideally, I'll have it read from a list, but that's another issue.

PROBLEM: I don't know what functions to use or how to get them to read the response returned from nslookup out of the cmd prompt into a variable. I can split it down to the machine's name if it returns the entire text from the cmd prompt, but how do I pass returned info from nslookup to a variable (or the entire text of the window)?

It returns the data after running nslookup in the cmd window that I left open. I need to write the returned data to a text file. I've looked at StdInWrite and StdOutRead as well.

Thanks for any help or suggestions.

 

#include <GUIConstantsEx.au3>
#include <Constants.au3>
#include <MsgBoxConstants.au3>
#include <Array.au3>

;  Script Function: Run NSLookup using ".Domain.com" to make the entered name an FQDN so you don't need to type 
the FQDN each time.
;                   Enter machine name, click run nslookup and it prints to an open cmd prompt window
;                   Need the returned IP address to be printed to a text file (HOW DO I MAKE THAT DATA IN THE CMD PROMPT INTO A VARIABLE?

;   Script ideas: Set it to read a list of names from a text file or spreadsheet.
;   Set the return to priint to a text file or spreadsheet *** How do I read and return data from the cmd prompt window.

$domain = "" ; Add domain name here to complete the FQDN - Leave it empty if sharing offsite.


NSLOOKUP()

Func NSLOOKUP()
    ; Create a GUI with various controls.
    Local $hGUI = GUICreate(@ScriptName)
    Local $BTN_NSLOOKUP = GUICtrlCreateButton("Run NSLookup", 310, 140, 85, 25)
    Local $LBL_DNSNAME = GUICtrlCreateLabel("Enter the machine's DNS shortname (Don't use the FQDN)", 25, 40, 300, 20) ; If testing offsite, you may need to use the FQDN
    Local $INPT_DNSNAME = GUICtrlCreateInput("", 25, 60, 250, 25)
    Local $LBL_OUTPUT_IP = GUICtrlCreateLabel("", 25, 100, 390, 25)

    ; Display the GUI.
    GUISetState(@SW_SHOW, $hGUI)

    ; Loop until the user exits.
    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop

            Case $BTN_NSLOOKUP
                $INPT_DNSNAME_RD = GUICtrlRead($INPT_DNSNAME)
                $PID = Run(@ComSpec & " /k NSLOOKUP " & $INPT_DNSNAME_RD & $domain, @SystemDir, @SW_SHOW)

                ProcessWaitClose($PID)


        EndSwitch
    WEnd

; Delete the previous GUI and all controls.
    GUIDelete($hGUI)
EndFunc   ;==>NSLOOKUP

 

Share this post


Link to post
Share on other sites

Please don't give me the entire answer. I'd like to figure out as much on my own as i can, but need some nudging in the right direction.

-snip-

It returns the data after running nslookup in the cmd window that I left open. I need to write the returned data to a text file. I've looked at StdInWrite and StdOutRead as well.

Ok, so what was the problem with StdOutRead  ?

Jos

 


SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites

Why a text file?  You can split it into variables directly out of stdout.  Heres a guess of something to do with nslookup

#include<array.au3>

$sCommands = 'nslookup www.microsoft.com'
$iPID = Run(@ComSpec & " /c " & $sCommands, "", @SW_HIDE , $stdout_child)

$sOutput = ""

 While 1
        $sOutput &= StdoutRead($iPID)
        If @error Then
            ExitLoop
        EndIf
 WEnd

 $aOut = stringsplit($sOutput , @LF , 2)
 local $aRtn[ubound($aOut) - 4]
 $aRtn[0] = "New Variables"

 For $i = 5 to ubound($aOut) - 1
     If StringLen($aOut[$i]) > 1 Then
         Assign("Address" & $i - 4 , stringstripWS($aOut[$i] , 8))
        $aRtn[$i - 4] = "Address" & $i - 4 & " = " & eval("Address" & $i - 4)
    EndIf
 Next

_ArrayDisplay($aRtn)

 


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

Share this post


Link to post
Share on other sites

@ Jos - Thanks for the reply.  

I haven't seen any data returned with StdOutRead. Clearly, I'm doing something wrong. :-)

Using the same code above and adding the two lines below to the loop returns an empty variable.

While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop

            Case $BTN_NSLOOKUP
                $INPT_DNSNAME_RD = GUICtrlRead($INPT_DNSNAME)
                $PID = Run(@ComSpec & " /k NSLOOKUP " & $INPT_DNSNAME_RD & $domain, @SystemDir, @SW_SHOW)

                ProcessWaitClose($PID)  ; ***** NEW LINE *****

                $IP = StdoutRead($PID)  ; ***** NEW LINE *****

                MsgBox(0, '', "IP = " & $iP)

        EndSwitch
    WEnd

 

Share this post


Link to post
Share on other sites

Did you check the helpfile for the Run() prerequisites for StdOutRead()?

Jos

 

Yes, but it looks like I should read it again. (I'm getting over a neck injury and eager to get my brain working again now that I can sit up after being out for 3 weeks. They gave me painkillers 2 days ago and I'm a little cloudy). Very tired of doing nothing. Stupid neck. :(

I'll read it again and tinker with things this afternoon. I'll reach out tomorrow if I'm still stuck.

Thank you to both of your for responses....

Share this post


Link to post
Share on other sites

Please don't give me the entire answer. I'd like to figure out as much on my own as i can, but need some nudging in the right direction.

It was at your own request, but you simply need to check out the example provided carefully and focus on the Run(). ;)

Jos


SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites

It was at your own request, but you simply need to check out the example provided carefully and focus on the Run(). ;)

Jos

Thanks for pointing me the right direction. Very much appreciated! 

I think I'm a little confused about whether i need to create 2 separate scripts, or if I can do it all in one, or if I need to do it with 2 and then use one as an included file. I'm guessing technically, it could be done any way, but what would the appropriate method be given my overall task?

 

Share this post


Link to post
Share on other sites

Your script is nearly correct, so no major changes needed.
Stop thinking and start reading the part I pointed you to and simply apply the fix. ;)
 

Jos 


SciTE4AutoIt3 Full installer Download page   - Beta files       Read before posting     How to post scriptsource        Forum Rules
 
Live for the present,
Dream of the future,
Learn from the past.
  :)

Share this post


Link to post
Share on other sites

Your script is nearly correct, so no major changes needed.
Stop thinking and start reading the part I pointed you to and simply apply the fix. ;)
 

Jos 

Even easier than I would have thought. Thanks for the help!!

Answer was proper placement for $STDOUT_CHILD

#include <AutoItConstants.au3>
#include <GUIConstantsEx.au3>
#include <Constants.au3>
#include <MsgBoxConstants.au3>
#include <Array.au3>


;  Script Function: Run NSLookup using domain.com to make the entered name an FQDN so you don't need to type the entire FQDN

;   Script ideas: Set it to read a list of names from a text file or spreadsheet.
;   Set the return to priint to a text file or spreadsheet *** How do I read and return data from the cmd prompt window.

Dim $IP
$domain = ""  ;Enter your primary DNS suffix as .name.com

NSLOOKUP()

Func NSLOOKUP()
    Local $hGUI = GUICreate(@ScriptName)
    Local $BTN_NSLOOKUP = GUICtrlCreateButton("Run NSLookup", 310, 140, 85, 25)
    Local $LBL_DNSNAME = GUICtrlCreateLabel("Enter the machine's DNS shortname (Don't use the FQDN)", 25, 40, 300, 20)
    Local $INPT_DNSNAME = GUICtrlCreateInput("", 25, 60, 250, 25)
    Local $LBL_OUTPUT_IP = GUICtrlCreateLabel("", 25, 100, 390, 25)


    GUISetState(@SW_SHOW, $hGUI)

    While 1
        Switch GUIGetMsg()
            Case $GUI_EVENT_CLOSE
                ExitLoop

            Case $BTN_NSLOOKUP
                $INPT_DNSNAME_RD = GUICtrlRead($INPT_DNSNAME)

                Local $PID = Run(@ComSpec & " /k NSLOOKUP " & $INPT_DNSNAME_RD & $domain, @SystemDir, @SW_SHOW, $STDOUT_CHILD)

                ProcessWaitClose($PID)

                $IP &= StdoutRead($PID)

                MsgBox(0, '', "IP = " & $iP)

        EndSwitch
    WEnd


; Delete the previous GUI and all controls.
    GUIDelete($hGUI)
EndFunc   ;==>NSLOOKUP


Func _READFROMCONSOLE()
    If Not @Compiled Then
        MsgBox($MB_SYSTEMMODAL, "", "This script must be compiled in order to run the example.")
        Exit
    EndIf

    Local $sOutput
    While True
        $sOutput &= ConsoleRead()
        If @error Then ExitLoop
        Sleep(25)
    WEnd

; CHANGE THE LINE BELOW TO OUTPUT TO A TEXT FILE
    MsgBox($MB_SYSTEMMODAL, "", "Output from cmd prompt: " & @CRLF & @CRLF & $sOutput)
EndFunc   ;==>_READFROMCONSOLE

 

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

  • Similar Content

    • By Luigi
      Greetings,
      Is possible build a script to send/receive commands in "Native Messagin" ?

      If you install this extension:
      https://chrome.google.com/webstore/detail/native-messaging-example/mefhabneoickhhbiglkmehhmemefkopf/related
      And this complement:
      https://github.com/Mandar-Shinde/Google-Chrome-Native-Messaging/releases/download/V1.0/GoogleNativeClient.exe

      You have a work example to send / receive messages from Google Chrome's plugin and NativeMessagingApp.exe.

      I found the source NativeMessagingApp.exe's here:
      https://github.com/Mandar-Shinde/Google-Chrome-Native-Messaging
      I try build this script... But not work...
       
      #Region ;**** Directives created by AutoIt3Wrapper_GUI **** #AutoIt3Wrapper_Compression=4 #AutoIt3Wrapper_Outfile=C:\Users\Public\GoogleNativeClient\NativeMessagingApp2.exe #AutoIt3Wrapper_UseUpx=y #AutoIt3Wrapper_Change2CUI=y #EndRegion ;**** Directives created by AutoIt3Wrapper_GUI **** #NoTrayIcon #include-once #include <Array.au3> #include <JSMN.au3> ; https://github.com/chechelaky/AutoIt/blob/master/JSMN.au3 #include <Debug.au3> Global $msg = "@empty" Global Const $CLIENT_START = '{"text":"Client Started"}' Global Const $CLIENT_STOP = '{"text":"Client Stopped"}' Global Const $CLIENT_CLICK = '{"text":"Client Click"}' _DebugSetup("NativeMessagingApp2", True, 4, @ScriptDir & "\NativeMessagingApp2.log", True) Global $read, $json, $out = "" If IsArray($CmdLine) Then ;~ $msg = @LF & "Google Chrome Native Messaging App V1" & @LF & @LF & _ ;~ "GPLV3 software distributed under the License is distributed on an ""AS IS"" BASIS" & @LF & _ ;~ "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied." & @LF & _ ;~ "See the License for the specific language governing permissions and" & @LF & _ ;~ "limitations under the License." & @LF & @LF ;~ Local $size = UBound($CmdLine, 1) - 1 ;~ $msg &= "App running with args=" & $size & @LF ;~ For $ii = 0 To $size ;~ $msg &= $ii & " : " & $CmdLine[$ii] & @LF ;~ Next ;~ _DebugOut($msg) EndIf sendMessage($CLIENT_START) While Sleep(10) $read = ConsoleRead() If @error And $out Then _DebugOut("$read...............: " & $out) $json = Jsmn_decode($out) If @error Then _DebugOut("$json...............: @Error") Else _DebugOut("$json...............: @Ok") EndIf If IsObj($json) And $json.Exists("text") Then sendMessage('{"text":"' & $json.Item("text") & '"}') Else sendMessage('{"text":"@Error"}') EndIf $out = "" Else $out &= $read EndIf WEnd Func sendMessage($var) ConsoleWrite($var & @CRLF) _DebugOut("sendMessage===>" & $var) EndFunc ;==>Say  
      Edit the file:
      C:\Users\Public\GoogleNativeClient\com.google.chrome.example.echo-win.json

      And replace:
      "path": "NativeMessagingApp.exe",
      By:
      "path": "NativeMessagingApp2.exe",
      Then plugin call the AutoIt script...

      But is not functional...

       
      About the file mainwindow.cpp, have this function:
      inline QString sendMessage(QString data){ unsigned int len = data.length(); cout.write(reinterpret_cast<const char *>(&len), 4); cout << data.toUtf8().data() << flush; return ""; } How re-write this to AutoIt?
      How execute a flush?



      Best regards.
    • By roundar
      The helpfile says:

      That isn't the case. A single call to ConsoleRead() will return the entire stream and block until the stream has been closed. Does anyone know a way around this? This auto-it script is a child process of another, non-autoit program so StdoutRead (for child processes) will not work.
×
×
  • Create New...