Jump to content

Search strinmg in console window - impossible?


Ghost1982
 Share

Recommended Posts

Hello

 

I'm struggling with searching of defined text in console window. I.e. CMD.

I've created simple .bat file that displays:

 

Welcome

Hello World

 

Let's say I want to confirm if word "Hello" exists in console. Is something like this possible? I was playing around with STDRead but I'm always getting "Not found". My script:

 

$con = Run("test.bat","", "", $STDERR_CHILD + $STDOUT_CHILD)

$line = StdoutRead($con) - I'm assinging the text lines to variable
If StringInStr($line, "Hello") Then - search substring Hello
      MsgBox(0, "Found:", $line)
   ExitLoop
Else
      MsgBox(0, "Not found", $line)
    ExitLoop
EndIf

 

What am I doing wrong? I

Edited by Ghost1982
Link to comment
Share on other sites

4 minutes ago, JockoDundee said:

stdoutRead doesn’t block(wait).

you’re reading the output before it is generated.

(or you haven’t included all the code)

It's all code. How do I know when the output is generated? I'm using Run to get the information from it.

Link to comment
Share on other sites

1 hour ago, Ghost1982 said:

It's all code. How do I know when the output is generated? I'm using Run to get the information from it.

You have an ExitLoop statement but no loop.  So can’t be all the code.

But you do need a loop.  
My suggestion would be to put it in a loop that exits when StringLen($line)>0.

Then msgbox $line. 

 

Code hard, but don’t hard code...

Link to comment
Share on other sites

There's no need for a loop to grab the output unless you need it in pseudo real time, which would be rare.

If you are good with capturing the ouput when the command has finished, then look at the example for StdoutRead in the Help File.

Or here's a trimmed down example adapted from the Help File example:

#include <Constants.au3>

cmd_output_example()

Func cmd_output_example()
    Local $iPID     = 0
    Local $sOutput  = ""

    ;execute DIR command in current directory
    $iPID = Run(@ComSpec & ' /c DIR', "", @SW_HIDE, $STDERR_MERGED)
    If @error Then Exit MsgBox($MB_ICONERROR, "ERROR", "An error occurred executing command.")

    ;wait for process to end
    ProcessWaitClose($iPID)

    ;get output
    $sOutput = StdoutRead($iPID)

    ;Display output
    ConsoleWrite("Command Output:" & @CRLF & @CRLF)
    ConsoleWrite($sOutput & @CRLF)
EndFunc

 

Edited by TheXman
Link to comment
Share on other sites

12 hours ago, JockoDundee said:

You have an ExitLoop statement but no loop.  So can’t be all the code.

But you do need a loop.  
My suggestion would be to put it in a loop that exits when StringLen($line)>0.

Then msgbox $line. 

 

These are remains from previous code I was testing. But I have found a soluton. For some reason I had to add WinWait($con) before $line = StdoutRead($con)

Link to comment
Share on other sites

12 hours ago, TheXman said:

There's no need for a loop to grab the output unless you need it in pseudo real time, which would be rare.

If you are good with capturing the ouput when the command has finished, then look at the example for StdoutRead in the Help File.

Or here's a trimmed down example adapted from the Help File example:

#include <Constants.au3>

cmd_output_example()

Func cmd_output_example()
    Local $iPID     = 0
    Local $sOutput  = ""

    ;execute DIR command in current directory
    $iPID = Run(@ComSpec & ' /c DIR', "", @SW_HIDE, $STDERR_MERGED)
    If @error Then Exit MsgBox($MB_ICONERROR, "ERROR", "An error occurred executing command.")

    ;wait for process to end
    ProcessWaitClose($iPID)

    ;get output
    $sOutput = StdoutRead($iPID)

    ;Display output
    ConsoleWrite("Command Output:" & @CRLF & @CRLF)
    ConsoleWrite($sOutput & @CRLF)
EndFunc

 

Why ProcessWaitClose? It closes the main script.

Link to comment
Share on other sites

4 hours ago, Ghost1982 said:

Why ProcessWaitClose? It closes the main script.

If you looked up ProcessWaitClose in the Help File, there's absolutely NO WAY you should have come away thinking that the ProcessWaitClose function "closes the main script".  If you ran the example I provided, there's no way you could think that it "closes the main script".  If it did, then how would the example script be able to read and display the output of the command?  ProcessWaitClose doesn't close ANYTHING.  :doh:In this case, it WAITS until the process ($iPID) executing the command is complete before reading the Stdout of the command.  That ensures that you read ALL of the output.

 

Edited by TheXman
Link to comment
Share on other sites

7 hours ago, Ghost1982 said:

These are remains from previous code I was testing. But I have found a soluton. For some reason I had to add WinWait($con) before $line = StdoutRead($con)

For “some reason”?

The reason is as I stated originally:

Quote

stdoutRead doesn’t block(wait).

you’re reading the output before it is generated.

WinWait(), in this case, waits for the command window to appear, which apparently is long enough to let you capture the output.

However, this is a risky strategy for the general case, for instance if the processing in the command window took any real-time, as opposed to “echo Hello World”, you would miss it.

Either put it in a loop, or as Xman said, wait for the process close and get it all then.

Otherwise, you are likely to be disappointed at some point.

Code hard, but don’t hard code...

Link to comment
Share on other sites

@Ghost1982

you change your title to: "Search strinmg in console window - impossible?"

Is this mean that you search for CONOSOLE / CMD window which was opened by your Run() command or you mean that this consolwe window was opened by hand, or by another process (not related to your AutoIt script) ?

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

I have another problem. I thought It is able to read from every console, so I've tested it in simple CMD. But what if I run Windows application that then connects to console within it? So it connects to remote connection session. Like PuTTy or Reflection. I use Run with STDIN_CHILD but the app must go through other steps until it opens in console. As I understand the Run only reads output from the first step, so when I open only main .exe of he app.

If I do something like Run("Putty.exe","","", STIN_CHILD) I'm not yet in console but in Windows app. Is it possible to read and recognize a text when console opens? The same with Reflection or any other remote console apps. Can I do STDIN_CHILD but from particular window?

Edited by Ghost1982
Link to comment
Share on other sites

4 hours ago, Ghost1982 said:

If I do something like Run("Putty.exe","","", STIN_CHILD) I'm not yet in console but in Windows app. Is it possible to read and recognize a text when console opens? The same with Reflection or any other remote console apps. Can I do STDIN_CHILD but from particular window?

What do you propose to do with the STDIN in your snippet above?  STDIN is used for input not ouput.

It would greatly benefit you and anyone trying to help you if you would refrain from using hypothetical questions or using examples that are not directly related to your issue.  The accuracy of the answers you get are usually directly related to the accuracy and details that you provide in your request for assistance.  Phrases like "what if", "if I do something like", "like putty or reflection", leave too much room for erroneous or misguided answers due to the lack of specificity in your questions which causes unnecessary frustration (on both sides).  Say exactly what application you are using, how you are using them,  and what exactly you are looking for assistance with.  Better yet, show your script so people can have a good understanding of what you are attempting to do, what you may be misunderstanding, and your level of expertise.

Not all consoles write to stdout and/or stderr.  Command line apps usually write to stdout and stderr.  Putty.exe is not a command line app.  However, Putty does show a console but it writes directly to and reads directly from that console, not to stdout/stderr/stdin.  Therefore, trying to capture the putty.exe conversation by reading stdout will not work.  Plink.exe, on the other hand, is the command line version of Putty.exe, and it DOES write to stdout and reads from stdin.  As such, you can have a conversation with the app thru reading stdout and writing to stdin (within the cmd console). 

Plink (and putty for that matter) are interactive apps.  So unless you plan to pass a command file to plink.exe, you will not only need to read stdout, but you would also need to write to stdin in order to execute your SSH commands.  I'm sure you were probably going to get around to bringing up that issue by saying something like "I have another problem" at some point.  I just though that I would proactively bring it to your attention now because you obviously don't have a good understanding of how to do what you are trying to do and all of the issues/obstacles involved.

To summarize...the more accurate your questions are, the more accurate your answers will be.  When it comes to support, nobody likes trying to hit a moving target.  And you have significantly moved the target from your initial post by not detailing exactly what you are trying to do and with which specific applications.

Edited by TheXman
Link to comment
Share on other sites

16 hours ago, TheXman said:

To summarize...the more accurate your questions are, the more accurate your answers will be.  When it comes to support, nobody likes trying to hit a moving target.  And you have significantly moved the target from your initial post by not detailing exactly what you are trying to do and with which specific applications.

Ok, so if you don't understand let me put as simple as it is. I want to know if I got Windows app that runs remote console within it, can I somehow read text from this console? Usually such connections are opened within the applications like PuTTy or Reflection, so I guess I cannot use Run command to get the output and search the console text. Maybe there's AutoIT command that allows to read from particular application window in that case, so I don't need to use Run? I don't have a script yet because I don't know what command to use if it's possible. I want to read from PuTTy or Reflection.

I was using CMD at first place just see how STDOUT works with console (in general).

Edited by Ghost1982
Link to comment
Share on other sites

2 hours ago, Ghost1982 said:

 I want to know if I got Windows app that runs remote console within it, can I somehow read text from this console? Usually such connections are opened within the applications like PuTTy or Reflection, so I guess I cannot use Run command to get the output and search the console text.

asked and answered.

18 hours ago, TheXman said:

Therefore, trying to capture the putty.exe conversation by reading stdout will not workPlink.exe, on the other hand, is the command line version of Putty.exe, and it DOES write to stdout and reads from stdin.  As such, you can have a conversation with the app thru reading stdout and writing to stdin (within the cmd console). 

but if you really, really need to use putty, you can try something* like this :)

Local $BadIdea = WinWaitActive("[TITLE:PuTTY]")
Local $GettingIt = False

While Not $GettingIt
    ControlSend($BadIdea, “”, “”,^a^c {PGDN} {ESC})
    $GarbageOut=ClipGet() 
    If $GarbageIn=$GarbageOut Then
       $GettingIt=True
    Else
       $GarbageIn=$GarbageOut
       $ScreenScrapage&=$GarbageOut
    EndIf
WEnd

ConsoleWrite($ScreenScrapage)

*Not tested

Code hard, but don’t hard code...

Link to comment
Share on other sites

16 hours ago, Ghost1982 said:

Ok, so if you don't understand let me put as simple as it is.

Oh, I understand your issue, and people like you, quite well.  It never ceases to amaze me how a person looking for help, that's so technically-challenge, could think it's wise to be a smart-ass to someone trying to help them.  That's just brilliant!  :muttley: 

Not only did I answer your previous question, I also gave you tips on how to get your questions answered quicker and more accurately.

Edited by TheXman
Link to comment
Share on other sites

  • 2 weeks later...
On 9/25/2020 at 3:47 PM, TheXman said:

Oh, I understand your issue, and people like you, quite well.  It never ceases to amaze me how a person looking for help, that's so technically-challenge, could think it's wise to be a smart-ass to someone trying to help them.  That's just brilliant!  :muttley: 

Not only did I answer your previous question, I also gave you tips on how to get your questions answered quicker and more accurately.

It looks like you're trying to be a "smart-ass" as well...just because you know something more. I'm always "amazed" with such individuals as well :)  If you claim understood the topic why asking to be more accurate.

Edited by Ghost1982
Link to comment
Share on other sites

On 9/25/2020 at 11:58 AM, JockoDundee said:

asked and answered.

but if you really, really need to use putty, you can try something* like this :)

Local $BadIdea = WinWaitActive("[TITLE:PuTTY]")
Local $GettingIt = False

While Not $GettingIt
    ControlSend($BadIdea, “”, “”,^a^c {PGDN} {ESC})
    $GarbageOut=ClipGet() 
    If $GarbageIn=$GarbageOut Then
       $GettingIt=True
    Else
       $GarbageIn=$GarbageOut
       $ScreenScrapage&=$GarbageOut
    EndIf
WEnd

ConsoleWrite($ScreenScrapage)

*Not tested

Yes, I've thought of that but it won't look good to select all text on screen. However, what about command ControlGetTet? Is it only for typical Win application window? also I was trying to play around with _GUICtrlEdit_SetSel but it looks like it's only when you create your own GUI window through script.

Link to comment
Share on other sites

5 hours ago, Ghost1982 said:

It looks like you're trying to be a "smart-ass" as well...just because you know something more. I'm always "amazed" with such individuals as well :) 

Wow, it took you 2 weeks to come up with that unoriginal reply?  Or, did your mommy just give you back your Internet privileges?  :rolleyes:  🤣

I was trying to help you but obviously you couldn't understand that for some reason (and I think we all know what that reason is). 

 

5 hours ago, Ghost1982 said:

If you claim understood the topic why asking to be more accurate.

Since you asked, here's your answer.  You said "I want to read from PuTTy or Reflection".  That implies that you either haven't chosen which app that you're going to use or that you are just throwing out hypothetical apps that you may want to work work with.  Well, which is it?  In either case, I wasn't going to waste my time giving you guidance towards a solution for Putty, for you to turn right back around and say that you want or wanted a solution for Reflection.  They're different apps and the solution for each would most likely be different too,  Until you know what you need, not what you want, you're just wasting time.  You may enjoy wasting time, but I don't.

Here's the bottom line:  You won't get the answers you're looking for until you learn how to ask better questions. 

 

Edited by TheXman
Link to comment
Share on other sites

7 hours ago, Ghost1982 said:

Yes, I've thought of that but it won't look good to select all text on screen.

No, it wouldn’t.  Scraping never does.  Though in this case, the code was primarily designed to provoke severe cognitive dissonance in anyone actually using it.

Just for the sake of completeness, would you like to state your reasons for not integrating using plink, which provides stream access to stdin and stdout?  

Code hard, but don’t hard code...

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...