Search the Community
Showing results for tags 'dos'.
-
GetOpt.au3 v1.3 If you've ever dabbled in C (or Python, Perl etc) then you might have heard of getopt() (Wiki entry). Well, I wrote this UDF to get that functionality into AutoIt. Some searching around here on the forum did turn up some other UDFs in this direction, but I decided to write my own port anyway and parallel the implementation in the C library. It's still missing a few things but on a whole it does the job really well. It's now pretty much complete. And I want to share it with you all. So here it is. If you want to handle the command line options passed to your script or program like a master, then this is the UDF for you! Main features: Parses DOS style options as well as GNU style options alike.Handles both short and long options.Define options that must have arguments when used.Define and handle suboptions (-s=foo,bar=quux,baz).Supports + and /- option modifiers.Casts string arguments to AutoIt variants, e.g. -a=yes becomes True.Easy access to any passed operand that's not an option.Some examples of invoking scripts: Script.au3 -a -b=10 --long-option file.txt Script.au3 /A /B:10 /Long-Option file.txtAs you see you can use both styles on the command line (as a matter of fact, at this moment you could even mix them but that wouldn't be good practice). In your script you just set the options you want to detect with _GetOpt_Set() and then iterate through each option with _GetOpt(). The 'file.txt' is available through _GetOpt_Oper(). See GetOpt-Example.au3 below for a step-by-step walkthrough of using GetOpt.au3. The UDF: GetOpt.au3 (+43) GetOpt-Example.au3: A demo of GetOpt.au3 #include <GetOpt.au3> #include <Array.au3> ; For demo purposes only. If 0 = $CmdLine[0] Then ; Create our own example command line. Run(FileGetShortName(@AutoItExe) & ' ' & FileGetShortName(@ScriptFullPath) & ' -a=no -b=42 -c=0.5 /Windows:' & @OSVersion & ' -z --required -s=foo,bar=quux,baz +p /-M -- -w=ignored Hello World!') Exit EndIf _GetOpt_Demo() Func _GetOpt_Demo() Local $sMsg = @ScriptName & ' for GetOpt v' & $GETOPT_VERSION & '.' & @CRLF & 'Parsing: ' & _ArrayToString($CmdLine, ' ', 1) & @CRLF & @CRLF; Message. Local $sOpt, $sSubOpt, $sOper ; Options array, entries have the format [short, long, default value] Local $aOpts[9][3] = [ _ ['-a', '--a-option', True], _ ['-b', '--b-option', False], _ ['-c', '--c-option', 'c option argument'], _ ['/W', '/Windows', 'windows style argument'], _ ; For demo purposes styles are mixed. ['-r', '--required', $GETOPT_REQUIRED_ARGUMENT], _ ; This option requires an argument. ['-s', '--suboption', $GETOPT_REQUIRED_ARGUMENT], _ ; option with suboptions. ['-p', '--plus', Default], _ ['/M', '/Minus', Default], _ ['-h', '--help', True] _ ] ; Suboptions array, entries have the format [suboption, default value] Local $aSubOpts[2][2] = [ _ ['foo', 47], _ ['bar', True] _ ] _GetOpt_Set($aOpts) ; Set options. If 0 < $GetOpt_Opts[0] Then ; If there are any options... While 1 ; ...loop through them one by one. ; Get the next option passing a string with valid options. $sOpt = _GetOpt('abcwr:s:pmh') ; r: means -r option requires an argument. If Not $sOpt Then ExitLoop ; No options or end of loop. ; Check @extended above if you want better error handling. ; The current option is stored in $GetOpt_Opt, it's index (in $GetOpt_Opts) ; in $GetOpt_Ind and it's value in $GetOpt_Arg. Switch $sOpt ; What is the current option? Case '?' ; Unknown options come here. @extended is set to $E_GETOPT_UNKNOWN_OPTION $sMsg &= 'Unknown option: ' & $GetOpt_Ind & ': ' & $GetOpt_Opt $sMsg &= ' with value "' & $GetOpt_Arg & '" (' & VarGetType($GetOpt_Arg) & ').' & @CRLF Case ':' ; Options with missing required arguments come here. @extended is set to $E_GETOPT_MISSING_ARGUMENT $sMsg &= 'Missing required argument for option: ' & $GetOpt_Ind & ': ' & $GetOpt_Opt & @CRLF Case 'a', 'b', 'c', 'w', 'p', 'm' $sMsg &= 'Option ' & $GetOpt_Ind & ': ' & $GetOpt_Opt $sMsg &= ' with value "' & $GetOpt_Arg & '" (' & VarGetType($GetOpt_Arg) & ')' If $GETOPT_MOD_PLUS = $GetOpt_Mod Then $sMsg &= ' and invoked with plus modifier (+' & $GetOpt_Opt & ')' ElseIf $GETOPT_MOD_MINUS = $GetOpt_Mod Then $sMsg &= ' and invoked with minus modifier (/-' & $GetOpt_Opt & ')' EndIf $sMsg &= '.' & @CRLF Case 'r' $sMsg &= 'Option ' & $GetOpt_Ind & ': ' & $GetOpt_Opt $sMsg &= ' with required value "' & $GetOpt_Arg & '" (' & VarGetType($GetOpt_Arg) & ')' If $GETOPT_MOD_PLUS = $GetOpt_Mod Then $sMsg &= ' and invoked with plus modifier (+' & $GetOpt_Opt & ')' ElseIf $GETOPT_MOD_MINUS = $GetOpt_Mod Then $sMsg &= ' and invoked with minus modifier (/-' & $GetOpt_Opt & ')' EndIf $sMsg &= '.' & @CRLF Case 's' $sMsg &= 'Option ' & $GetOpt_Ind & ': ' & $GetOpt_Opt $sMsg &= ' with required suboptions:' & @CRLF While 1 ; Loop through suboptions. $sSubOpt = _GetOpt_Sub($GetOpt_Arg, $aSubOpts) If Not $sSubOpt Then ExitLoop ; No suboptions or end of loop. ; Check @extended above if you want better error handling. ; The current suboption is stored in $GetOpt_SubOpt, it's index (in $GetOpt_SubOpts) ; in $GetOpt_SubInd and it's value in $GetOpt_SubArg. Switch $sSubOpt ; What is the current suboption? Case '?' $sMsg &= ' Unknown suboption ' & $GetOpt_SubInd & ': ' & $GetOpt_SubOpt $sMsg &= ' with value "' & $GetOpt_SubArg & '" (' & VarGetType($GetOpt_SubArg) & ').' & @CRLF Case 'foo', 'bar' $sMsg &= ' Suboption ' & $GetOpt_SubInd & ': ' & $GetOpt_SubOpt $sMsg &= ' with value "' & $GetOpt_SubArg & '" (' & VarGetType($GetOpt_SubArg) & ').' & @CRLF EndSwitch WEnd If $GETOPT_MOD_PLUS = $GetOpt_Mod Then $sMsg &= 'And invoked with plus modifier (+' & $GetOpt_Opt & ').' ElseIf $GETOPT_MOD_MINUS = $GetOpt_Mod Then $sMsg &= ' and invoked with minus modifier (/-' & $GetOpt_Opt & ')' EndIf Case 'h' MsgBox(0, 'GetOpt.au3', 'GetOpt.au3 example.' & @CRLF & _ 'Just try out some options and find out what happens!') Exit EndSwitch WEnd Else $sMsg &= 'No options passed.' & @CRLF EndIf $sMsg &= @CRLF If 0 < $GetOpt_Opers[0] Then ; If there are any operands... While 1 ; ...loop through them one by one. $sOper = _GetOpt_Oper() ; Get the next operand. If Not $sOper Then ExitLoop ; no operands or end of loop. ; Check @extended above if you want better error handling. $sMsg &= 'Operand ' & $GetOpt_OperInd & ': ' & $sOper & @CRLF WEnd Else $sMsg &= 'No operands passed.' & @CRLF EndIf MsgBox(0, @ScriptName, $sMsg) ; Let's see what we've got. _ArrayDisplay($GetOpt_Opts, '$GetOpt_Opts') _ArrayDisplay($GetOpt_Opers, '$GetOpt_Opers') _ArrayDisplay($GetOpt_ArgV, '$GetOpt_ArgV') Exit EndFunc Version 1.3: + Added support for -- (marks end of options). + Added support for + option modifiers e.g. +x. + Added support for /- option modifiers e.g. /-X. + Added _GetOpt_Sub to iterate through comma-separated suboptions like -s=a=foo,b=bar. * Changed $GETOPT_REQUIRED_ARGUMENT from keyword Default to Chr(127), keyword can now be used as an option argument. * Standardized comments and function headers. * Tidy-ed up source code. Version 1.2: + Support for required arguments with options, e.g. _GetOpt('ab:c') where -b=foo is valid and -b will return an error. + Added support for /C:foo (colon) when using DOS style. + Added optional auto-casting of arguments from Strings to AutoIt variants, e.g. -a=yes on the CLI would set the $GetOpt_Arg to True and not 'yes'. See __GetOpt_Cast. * Private __GetOpt_DOSToGNU to simplify code. Version 1.1: * Initial public release. If you encounter any bugs or have any suggestions, requests or improvements, then please let me know. Happy coding!
- 14 replies
-
- getopt
- command line
-
(and 6 more)
Tagged with:
-
Hello, I wrote a small AutoIt App which takes DOS formatted textfiles and forwards them to MS Word. I searched a lot for a programm which does this, but I didn't find one. The reason for it is an old DOS program, which is used a lot, even today. The user wanted to print the output of that programm with some other font-size, font-style and so on... We used WinPrint, but this is a printing only app, so no formatting can be done afterwards... The solution was, to print with the DOS prgramm to an file, e.g. C:\12345\output.txt ... then read this file, convert it to unicode, put this into word with some pre-defined font / page size and so on ... and then the user can re-format or print it now. Here is the main function of the Dos2Word programm I wrote: Func Convert2Word() ; keine datei da... If Not FileExists($sFilePath) Then Return ; noch in Beaarbeitung... If _WinAPI_FileInUse($sFilePath) Then Return ; nun aber... Local $sFilePathTemp = $sFilePath & "_" & _WinAPI_CreateGUID() & ".txt" FileMove($sFilePath, $sFilePathTemp, $FC_OVERWRITE) ; open word and create new document Local $oWord = _Word_Create() If @error Then ErrorExit("Fehler bei _Word_Create()") Local $oDoc = _Word_DocAdd($oWord) If @error Then ErrorExit("Fehler bei _Word_DocAdd()") ; seite definieren With $oDoc.PageSetup .PageHeight = $sPageHeight .PageWidth = $sPageWidth .TopMargin = $sTopMargin .BottomMargin = $sBottomMargin .LeftMargin = $sLeftMargin .RightMargin = $sRightMargin EndWith ; schrift und absatz With $oDoc.Range .Font.Name = $sFontName .Font.Size = $sFontSize EndWith With $oDoc.Range.ParagraphFormat .SpaceBefore = 0 .SpaceAfter = 0 .LineUnitBefore = 0 .LineUnitAfter = 0 .LineSpacingRule = 0 EndWith Local $hFile = FileOpen($sFilePathTemp, BitOR($FO_READ, $FO_BINARY)) Local $iError Local $iLine = 1 Do Local $sLine = FileReadLine($hFile, $iLine) $iError = @error $iLine += 1 ; ignore special escape line of cm.exe If StringLeft($sLine, 2) = Chr(27) & Chr(64) Then $sLine = StringTrimLeft($sLine, 2) $oDoc.Range.insertAfter(_WinAPI_MultiByteToWideChar($sLine, $sCodePage, 0, True) & @CRLF) Until $iError <> 0 ; und am ende löschen, sofern gewünscht FileClose($hFile) If $sFilesDelete <> "0" Then FileDelete($sFilePathTemp) EndFunc ;==>Convert2Word The Homepage of the program is here: https://mcmilk.de/projects/Dos2Word/ The full source code and precompild signed binaries for 32bit and 64bit systems are also there, the License is GPLv2 With best regards, Milky Maybe someone finds it useful too
-
I need to be able to issue a command line which has a folder in parentheses as attrib +s +h "absolute folder to hide" I've read through many posts here but nothing quite hacks how to use a variable as the folder in parentheses. I've tried Local $dosattrib = "attrib +s +h " & ""$hidFolder"" ; $hidFolder built up from decrypted encrypted C:\Hidden Folder which I do not want visible when compiled version is reverse engineered which errors with excess parentheses but in single "" it doesn't work. There seems to be a relatively complicated method to make it work but surely there's a simple way?
-
Hi all, I need to start a script that include: - admin privileges - multiple cmd commands - no bat, no exe, no tmp files created anywhere (especially in the user temp folder) In a bat file it would be simple, but users shouldn't see what commands I'm sending. Example of the script: echo off cls echo. echo I AM A TOOL echo. echo NOTE: echo - note 1 echo - note 2 echo - etc set USER1=0 set COMPUTER1=0 if /i %username% equ user.user ( set USER1=1 set COMPUTER1=1 ) if /i %username% equ another.user set USER1=1 if /i %computername% equ notebook set COMPUTER1=1 if %USER1% EQU 1 ( if %COMPUTER1% EQU 1 ( reg delete "HKLM\SOFTWARE\blablabla" /f ) else ( echo Computer not authorized. Contact assistance.) ) else ( echo User not authorized. Contact assistance.) echo. pause exit With the send("") is a disaster. I'm a noob here, so what can I do? EDIT: OR ELSE I explain the situation and what I need, so if there is a simple solution I can use that. SITUATION: our domain users have Users rights on the machine. Some of them need administrator rights. We create a local user with administrator rights, so that the users must insert username and password when asked to run something with administrator rights. We have an internal domain group policy that blocks EXE, BAT, COM, TMP files from the user local temp directory, for a security reason (malware). That also blocks most software installation. But some users are often out of office, away from workplace and in another country, they need a complete control on their computers. WHAT I NEED: I need to check the username and the computer name. If the username is the one with local administrator rights and the computer name is a computer that is qualified to temporary remove the policy, then I need to execute a REG DELETE command with administrator rights. I hope I explained myself. Thank you very much.
-
Version 1.3
1,741 downloads
Hello Everyone , Are you tired of searching the forum for getting both the exit code & the stdout output? Then your are in the right place! With this UDF you can get the both output & exit code of the command or the console app! Or you can get the exit code of another process without having to use RunWait... Features: 1. Simple & Lightweight (15 KB) 2. Detailed comments & description 3. Flexible functions with many optional parameters A BIG THANKS TO PsaltyDS for the functions! 2 of the (main) functions in the UDF are his work List of functions: -
I have problems running both Bat files and Command line instructions. This function hopefully shows what I have tried so far Global $fFileToCreate = "", $DOS ScanFilm($fFileToCreate) Func ScanFilm($fFileToCreate) MsgBox($MB_SYSTEMMODAL, "Scanning Status", $fFileToCreate) ; $DOS = Run(@ComSpec & " /c " & "scan.bat" & @CRLF, "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD) $DOS = Run(@ComSpec & " /k " & "ncat 192.168.1.6 80 <scant.txt >scanrep", "", @SW_HIDE, $STDERR_CHILD + $STDOUT_CHILD) ; $DOS = _RunDOS("ncat 192.168.1.6 80 <scant.txt >scanrep") ProcessWaitClose($DOS) $Message = StdoutRead($DOS) MsgBox($MB_SYSTEMMODAL, "Stdout Read:", $Message) Endfunc My first attempt running scan.bat reveals a bug in cmd.exe where the result of echo !SR | ncat 192.168.1.6 80 > scanrep is C:\S3_GUI\ncat>scan.bat C:\S3_GUI\ncat>echo scant.txt | ncat 192.168.1.6 80 1>scanrep Ncat: . C:\S3_GUI\ncat> note the added '1' which then throws the error, (when client is connected), "File or directory not found" so the command fails. This has been run on four different computers running Windows 7 with same result. Next using Run() seems to truncate the command so $DOS reads: Using _RunDOS() doesn't throw any error but MsgBox() is empty.
-
Hey guys! I need your help again. So I am working on a Project with which I can Logoff a User in a Terminal-Server (Windows Server 2012 R2), logged in as Admin. Then backup the users partition and log him back in. Sounds pretty easy for you guys, right? So my problem is... I seem to not be able to get the User ID. You can see and display the ID in a textfile with: Run("query user>>c:\users\example\desktop\helpmeguys.txt") This line just writes a textfile of "query user" on the desktop. This is an example on what it looks like: BENUTZERNAME SITZUNGSNAME ID STATUS LEERLAUF ANMELDEZEIT >wg console 2 Aktiv 17 25.07.2016 08:19 What I need right now is the ID. Any Idea on how to read it off of the Textfile? Please give me examples because I am still a rookie! With kind regards Eddi96
-
Process UDF, Get both the output & the exit code!
TheDcoder posted a topic in AutoIt Example Scripts
Hello Everyone , Are you tired of searching the forum for getting both the exit code & the stdout output? Then you are in the right place! With this UDF you can get the both output & exit code of the command or the console app! Or you can get the exit code of another process without having to use RunWait... Features: 1. Simple & Lightweight (15 KB) 2. Detailed comments & description 3. Flexible functions with many optional parameters A BIG THANKS TO PsaltyDS for the functions! 2 of the (main) functions in the UDF are his work List of functions: Downloads: Grab the latest (in development) code from GitHub Hope it may help you, TD P.S Icon made by Freepik from www.flaticon.com, Modified by TheDcoder -
I have been wracking my brains today trying to figure out how to send a control character to a DOS command I initiate within a script. I am doing this little project to eventually add a GUI to some older DOS based apps still in use. (Not everyone appreciates the fine art of command line execution I guess ) Anywho, to test my scripting and what I was able to dig up, I came up with the following. (Yes, I know AutoIT has a ping function, DOS ping was what I came up with to test sending commands to, it is not the final program) #cs ---------------------------------------------------------------------------- AutoIt Version: 3.3.12.0 Author: myName Script Function: Template AutoIt script. #ce ---------------------------------------------------------------------------- ; Script Start - Add your code below here #include <ButtonConstants.au3> #include <EditConstants.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <Constants.au3> #include <process.au3> Opt("GUIOnEventMode", 1) #Region ### START Koda GUI section ### $Main = GUICreate("Ping Now", 547, 62, 192, 124) GUISetFont(10, 400, 0, "MS Sans Serif") GUISetOnEvent($GUI_EVENT_CLOSE, "MainClose") GUISetOnEvent($GUI_EVENT_MINIMIZE, "MainMinimize") GUISetOnEvent($GUI_EVENT_MAXIMIZE, "MainMaximize") GUISetOnEvent($GUI_EVENT_RESTORE, "MainRestore") $tbPingURL = GUICtrlCreateInput("", 16, 16, 425, 24) GUICtrlSetOnEvent($tbPingURL, "tbPingURLChange") $btnPingStart = GUICtrlCreateButton("Ping Now", 456, 16, 75, 25) GUICtrlSetOnEvent($btnPingStart, "btnPingStartClick") GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### Global $srPID While 1 Sleep(100) WEnd Func btnPingStartClick() Local $sURL = GUICtrlRead($tbpingURL),$stdOutLine MsgBox(0,"Ping URL","Reading URL: "&$sURL) ;ignored as I got tired of typing $srPID = Run(@ComSpec&" /c "&"ping -t yahoo.com","",@SW_HIDE,$STDIN_CHILD + $STDOUT_CHILD) ConsoleWrite("Running with PID: "&$srPID&@CRLF) Sleep(1000) EndFunc Func MainClose() ;ControlSend(@ComSpec,"","",Chr(3),1) ;ConsoleWrite(_ProcessGetName($srPID)) $charout=StdinWrite($srPID,Chr(3)) ConsoleWrite($charout&" - "&@error&@CRLF) StdinWrite($srPID) ;ProcessWait($srPID) ProcessWaitClose($srPID) Exit EndFunc Func MainMaximize() EndFunc Func MainMinimize() EndFunc Func MainRestore() EndFunc Func tbPingURLChange() EndFunc When I close the resulting window, I am expecting a CTRL+c to be sent to the running Ping command. Instead, I get a result code back implying that the command was send but nothing happens after that. Ping continues to run in the background till I end its process through Task Manager. When I end the process, the script closes, provided I attempt to close the GUI window (Func MainClose()). If I do not try to close the GUI first and end the ping process through task manager, I get a '0' as the result code for StdInWrite. The PID returned is NOT that of the child process initiated by the Run command but that of the cmd.exe that is started to run the Ping command within. Leaving off the @comspec portion of the Run statement makes no difference, the ping continues to run till ended. Any suggestions? I noted that other queries about sending control keys to DOS commands have been posted in the past but I didn't really pick up on a solution.
-
I am new to AutoIt, so please be kind. I'm writing a script that will run an executable that upgrades OpenSSH on several remote computers. It first uninstalls the old version then installs the new version. I'm all the way through, but have run into one problem. When it gets to the part of the executable where it actually starts installing/extracting all the files, about midway through, it stops and a DOS box pops up with a ____________ key already exists. Overwrite (y/n)? There are actually 3 boxes in a row with the same "Overwrite (y/n)?" prompt. I've tried using Send ("{y}") Send ("{Enter}") but no luck. Any ideas please?
-
I have installed the amazon command-line interface (http://aws.amazon.com/cli/) and have it working in my cmd prompt dos window. For example, If I set the working directory to C:UsersAdministrator and run the command below to upload a file to the S3 service: aws s3 cp C:UsersAdministratorDesktopvpntimeout_text.txt s3:/clustertesting/vpntimeout_text.txt I get the response: upload: myfolder/file1.txt to s3:/mybucket/myfolder/file1.txt However, trying to replicate the same command in Autoit with : --------------------------------------------------------------------------- #include <Constants.au3> ;$ami_ID = "ami-1a0d912a" ;$n=1 ; Command: ;$DOS = Run(@ComSpec & ' /k' & "aws ec2 run-instances " & $ami_ID & " -n " & $n & " -k windows --instance-type t1.micro -g quicklaunch-1", "", "", $STDERR_CHILD + $STDOUT_CHILD) $workingdir = "C:UsersAdministrator" ConsoleWrite($DOS & @CRLF) Local $output While 1 $line = StdoutRead($DOS) If @error Then ExitLoop ConsoleWrite($line) Wend ConsoleWrite($line & @CRLF) ConsoleWrite("error = " & @error & @CRLF) --------------------------------------------------------------------------- The dos window flashes up and a PID is returned in $DOS, and the error value is zero. However, unlike my command performed in the command prompt, the autoit version does not upload my file to S3 and does not print a response. Does anyone see what I've done wrong in Autoit? From what I can tell me code should be performing the same command sorry I haven't used the code editor for this post- it failed to work in two browsers o I ended up just pasting the raw text
- 4 replies
-
- run×runwait×dos×stdout×cmd×
- run
- (and 4 more)
-
I need help with a DOS line I am trying to send to another computer. I am using a program called psexec to connect to another computer on my domain and perform a cmd-command on that computer remote. The software works great, but when I try to automate this and put both commands in 1 line it wont work example: psexec hostname cmd (this starts the service and after 5-10 seconds it is ready) then I want it to do this command after loading is done: net localgroup administrators username /add but when I try these two commands together it wont start the second command. both & and && wont work. Kind Regards, Akarillon
-
I have been searching for 5 hours now, and I can't find any information about how to send DOS-commands to another computer remote without having the script on the computer. And I could go another way by editing Registry by remote, but I don't know how or if I can add users(domain) to be an administrator account. (I know this is not really that related to AutoIT, but it is part of my script). All help will be appreciated Kind Regards, Akarillon
-
I am trying to get information from a DOS-window by getting a spesific line of information (SID) I found the _RunDOS ( $sCommand ) function, but I could not find any way to get the information or store it in any way(variable/notepad/....) Anyone got any idéa? =) Can be a dos command, VBScript or anything, just need it stored somewhere I can read Kind Regards, Akarillon