how to post a file or stdout into a http server? - windows

I would like to execute some command then send them into my web server for analysis.
somethink like :
wmic csproduct get | wget http://someserver/cgi-bin/hello.pl
Except that wget is not delivered out-of-the-box by Microsoft.
How can I make the same using stuff that are delivered with Windows 2000 and futher? Can vbscript do the job?

Since you executing some commands to get your information, may be it would be more native to use a command shell environment?
How about PowerShell?
(New-Object System.Net.WebClient).UploadString("http://someserver/cgi-bin/hello.pl", (Get-WMIObject Win32_BIOS) )
read about the UploadString() method here
If you still want to stick to a vbscript solution, here is a sample code which accepts a text from stdin and posts it to your server:
Dim inp, http_req
inp = inp & WScript.StdIn.ReadAll()
WScript.Echo "Input: " & inp
Set http_req = CreateObject("WinHTTP.WinHTTPRequest.5.1")
http_req.open "POST", "http://someserver/cgi-bin/hello.pl", false
http_req.setRequestHeader "Content-Type", "text/plain"
http_req.send inp
The minimum requirements seems to be Windows 2000 Professional with SP3 , i personnaly tested the script with Windows XP.

Related

Download web content through CMD

I want some way of getting an online content on the command prompt window (Windows CMD).
Imagine some content online stored either on a hosting service or the MySql database provided to you by that hosting service. It can be any data stored in any form. I just want to remotely view it with the help of a CMD window anywhere in the world. What command should I be using?
To make it more clear, lets just say you have one day to prepare for your exam. Rather than preparing for it, you are making a plan to cheat.
Now your exam is going to be conducted on a computer that has been allotted to you and you are not allowed to use a browser or download any new application on the PC. But you can use Command Prompt, so your task being a cheat is to put the answers somewhere online. You cannot install anything new.
How will you go about if you are stuck in the above scene?
P.S This is for educational purpose only. I have no such such exams.
It depends entirely on how the content is stored and accessed. CMD knows how to get things from SMB network shares (\computername\folder), but you need to run a program to access most other stuff. (eg: sqlcmd for a database)
CMD does not support downloading web content. You will need to use another program to connect to the website and download the page. Obviously a browser would work. Another option is to download wget.exe from UnxUtils. Or use another scripting language like PowerShell or Wscript.
If you have access to launch PowerShell (pre-installed on Windows 7-10), you can use the .NET library to download web resources.
PS> Invoke-Webrequest 'www.mywebsite.com/myfile.txt' -OutFile '.\myfile.txt'
This will use .NET to connect to the page and download it into the local directory. To download to another directory or filename, change the -OutFile argument.
To launch this from CMD, go into a PowerShell prompt by simply typing powershell in CMD, and running the PS commands from there. Alternatively, you can run PS commands from CMD using the powershell -c command.
powershell.exe -c "invoke-webrequest 'www.mywebsite.com/myfile.txt' -outfile .\myfile.txt"
You can check this question.The easiest way is with bitsadmin command:
bitsadmin /transfer myDownloadJob /download /priority normal http://downloadsrv/10mb.zip c:\10mb.zip
You can try also winhttpjs.bat:
call winhhtpjs.bat https://example.com/files/some.zip -saveTo c:\somezip.zip
Windows 10 build 17063 and later ships curl.exe (ref: https://techcommunity.microsoft.com/t5/containers/tar-and-curl-come-to-windows/ba-p/382409). Assuming you don't need to support earlier Windows versions, including earlier Windows 10 builds, you can use it in your batch files like this
curl http://example.com/ --output content.txt
notepad content.txt
Set Arg = WScript.Arguments
set WshShell = createObject("Wscript.Shell")
Set Inp = WScript.Stdin
Set Outp = Wscript.Stdout
On Error Resume Next
Set File = WScript.CreateObject("Microsoft.XMLHTTP")
File.Open "GET", Arg(1), False
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
txt=File.ResponseText
'Putting in line endings
Outp.write txt
If err.number <> 0 then
Outp.writeline ""
Outp.writeline "Error getting file"
Outp.writeline "=================="
Outp.writeline ""
Outp.writeline "Error " & err.number & "(0x" & hex(err.number) & ") " & err.description
Outp.writeline "Source " & err.source
Outp.writeline ""
Outp.writeline "HTTP Error " & File.Status & " " & File.StatusText
Outp.writeline File.getAllResponseHeaders
Outp.writeline LCase(Arg(1))
End If
General Use
Filter is for use in a command prompt. Filter.vbs must be run with cscript.exe. If you just type filter it will run a batch file that will do this automatically.
filter subcommand [parameters]
Filter reads and writes standard in and standard out only. These are only available in a command prompt.
filter <inputfile >outputfile
filter <inputfile | other_command
other_command | filter >outputfile
other_command | filter | other_command
Web
filter web webaddress
filter ip webaddress
Retrieves a file from the web and writes it to standard out.
webaddress - a web address fully specified including http://
Example
Gets Microsoft's home page
filter web http://www.microsoft.com
Filter with 19 example command prompt scripts avaialable at https://onedrive.live.com/redir?resid=E2F0CE17A268A4FA!121&authkey=!AAFg7j814-lJtmI&ithint=folder%2cres
Apart from VBScript & JScripts, there's a utility (resides with CMD) on Windows which can be run from CMD (if you have write access):
set url=https://www.nsa.org/content/hl-images/2017/02/09/NSA.jpg
set file=file.jpg
certutil -urlcache -split -f %url% %file%
Cmdlets in Powershell:
$url = "https://www.nsa.org/content/hl-images/2017/02/09/NSA.jpg"
$file = "file.jpg"
$ProgressPreference = "SilentlyContinue";
Invoke-WebRequest -Uri $url -outfile $file
.Net under PowerShell:
$url = "https://www.nsa.org/content/hl-images/2017/02/09/NSA.jpg"
$file = "file.jpg"
# Add the necessary .NET assembly
Add-Type -AssemblyName System.Net.Http
# Create the HttpClient object
$client = New-Object -TypeName System.Net.Http.Httpclient
$task = $client.GetAsync($url)
$task.wait();
[io.file]::WriteAllBytes($file, $task.Result.Content.ReadAsByteArrayAsync().Result)
C# application built on command-line with csc.exe:
https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-options/command-line-building-with-csc-exe
using System;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
namespace DownloadImage
{
class Program
{
static async Task Main(string[] args)
{
using var httpClient = new HttpClient();
var url = "https://www.nsa.org/content/hl-images/2017/02/09/NSA.jpg";
byte[] imageBytes = await httpClient.GetByteArrayAsync(url);
using var fs = new FileStream("file.jpg", FileMode.Create);
fs.Write(imageBytes, 0, imageBytes.Length);
}
}
}
Built in Windows applications. No need for external downloads.
Tested on Win 10

Install inf driver with VBScript on Windows 7

I am trying to write a VBS script that install an USB/Ethernet adapter on Windows 7.
I've got a .INF file for this device.
I first tried:
Dim WshShell, res
Set WshShell = WScript.CreateObject("WScript.Shell")
res = WshShell.Run(WshShell.ExpandEnvironmentStrings( "%SystemRoot%" ) & "\System32\InfDefaultInstall.exe "" C:\Users\Me\Driver.inf """, 1, True)
res equaled 2.
Then I searched another way to do that and I found:
Dim WshShell, res
Set WshShell = WScript.CreateObject("WScript.Shell")
res = WshShell.Run(WshShell.ExpandEnvironmentStrings( "%SystemRoot%" ) & "\System32\rundll32.exe SETUPAPI.DLL,InstallHinfSection DefaultInstall 132 ""Driver.inf""", 1, True)
res equals 0 but I've got an error popup Installation failed.
What's wrong with my code? For the record, the script is launched with administration rights.
EDIT
I've tried to execute the first command directly in prompt and got: The inf file you selected does not support this method of installation..
Nothing happens with second command in prompt.
This is very weird because I can install the driver "manually" when I launch the device manager and select the inf file (with a warning: Windows can't verify the publisher of this driver software.):
Once the driver is installed, the class installer property shows NetCfgx.dll,NetClassInstaller. Could it be used?
I also tried with devcon with no success (program returns devcon.exe failed).
How about this way:
1)If you're using "Windows 7", why not take advantage of the driver pre-staging utility that is built right into the OS? W7 ships with a driver utility called "PNPUTIL". Issuing a command as such will add the drivers:
PNPUTIL -a "X:\Path to Driver File\Driver.inf"
This will process the INF and copy the CAT/SYS/INF (and any DLL, EXE, etc) into the "DriverStore" folder... which is the same place Windows stores all the in-built drivers ready for auto plug-and-play instalaltion.
2)If that's not an option for you, look for "DPInst.exe" (or "DPInst64.exe" for 64-bit systems). These are available as part of the Windows PDK (available free from Microsoft) and will process all INFs in the location you put the file and attempt to pre-stage them. This method tries to copy files to the "Drivers", "CatRoot", and "INF" locations which are not as reliable... and it can occassionally fail to copy required DLLs to "System32" folders etc... but 99% of the time (for simple drivers) it just works. I can arrange to send them to you if you can't find them.
Since I found the option (1) above, that has been my best friend. I use option 2 to isntall Canon USB printers and scanners on our base images, etc... so I know that works too.
I had same problem and solved it by explicitly using ASCII version of InstallHinfSection entry point:
res = WshShell.Run("%Comspec% /C %SystemRoot%\System32\rundll32.exe SETUPAPI.DLL,InstallHinfSectionA DefaultInstall 132 ""Driver.inf""", 1, True)
There is probably a better solution, though (like hinting at the script engine which unicode/ASCII flavor to use).
Also I'm using EN-US system so this workaround may fail on more exotic locales.
Try this:
res = WshShell.Run("%Comspec% /C %SystemRoot%\System32\rundll32.exe SETUPAPI.DLL,InstallHinfSection DefaultInstall 132 ""Driver.inf""", 1, True)

How to add a Local Printer using VBScript on Windows 7?

I have a Windows 7 64bit pc, I'm trying to add a Local Printer which automatically installs the driver and shares the printer once it is done.
The port is a Loopback IP Address (127.0.0.1) and it uses the Zebra (ZDesigner LP 2844) Driver. (Which you can get here: http://www.zebra.com/us/en/support-downloads/desktop/lp-2844.html )
My current script works great on XP but not so good on Windows 7. It comes up with the error
"Microsoft VBScript runtime error:ActiveX component can't create object: 'Port.Port.1' for my script AddPort.vbs
The following script is called AddPort.vbs
'ADDING:
dim oPort
dim oMaster
set oPort = CreateObject("Port.Port.1")
set oMaster = CreateObject("PrintMaster.PrintMaster.1")
wscript.echo "Adding port to local machine...."
'Indicate where to add the port. Double quotes ("" ) stand for the local computer, which is the default, or put "\\servername"
oPort.ServerName = ""
'The name of the port cannot be omitted.
oPort.PortName = "CustomPortName"
'The type of the port can be 1 (TCP RAW), 2 (TCP LPR), or 3 (standard local).
oPort.PortType = 3
'For TCP RAW ports. Default is 9100.
oPort.PortNumber = 9101
'Try adding the port.
oMaster.PortAdd oPort
'Test for the status.
If Err <> 0 then
wscript.echo "Error " & Err & " occurred while adding port"
End If
The Following script is called AddPrinter.vbs
This script shows the error "Microsoft VBScript runtime error:ActiveX component can't create object: PrintMaster.PrintMaster.1
' Adding a Printer
' The sample code in this section creates any required objects, adds a printer to a remote server, and configures some driver and port information.
dim oMaster
dim oPrinter
wscript.echo "Adding VirtualPrinter printer to local machine...."
'The following code creates the required PrintMaster and Printer objects.
set oMaster = CreateObject("PrintMaster.PrintMaster.1")
set oPrinter = CreateObject("Printer.Printer.1")
'The following code specifies the name of the computer where the printer will be added. To specify the local
'computer, either use empty quotes (“”) for the computer name, or do not use the following line of code. If
'ServerName is not set, the local computer is used. Always precede the name of a remote computer with two backslashes (\\).
oPrinter.ServerName = ""
'The following code assigns a name to the printer. The string is required and cannot be empty.
oPrinter.PrinterName = "VirtualPrinter"
'The following code specifies the printer driver to use. The string is required and cannot be empty.
oPrinter.DriverName = "ZDesigner LP 2844"
'The following code specifies the printer port to use. The string is required and cannot be empty.
oPrinter.PortName = "LoopBack"
'The following code specifies the location of the printer driver. This setting is optional, because by default
'the drivers are picked up from the driver cache directory.
'oPrinter.DriverPath = "c:\drivers"
'The following code specifies the location of the INF file. This setting is optional, because by default the INF
'file is picked up from the %windir%\inf\ntprint.inf directory.
'oPrinter.InfFile = "c:\winnt\inf\ntprint.inf"
oPrinter.PrintProcessor = "winprint"
'The following code adds the printer.
oMaster.PrinterAdd oPrinter
'The following code uses the Err object to determine whether the printer was added successfully.
if Err <> 0 then
wscript.echo "Error " & Err & " occurred while adding VirtualPrinter"
else
wscript.echo "Printer added successfully"
end if
' To configure other printer settings, such as comments, create a Printer object and then call PrintMaster's method PrinterSet.
wscript.echo "Configuring printer...."
oPrinter.Comment = "Virtual printer to capture labels"
oPrinter.ShareName = "VirtualPrinter"
oPrinter.Shared = true
oPrinter.Local = true
oMaster.PrinterSet oPrinter
if Err <> 0 then
wscript.echo "Error " & Err & " occurred while changing settings for VirtualPrinter"
end if
Is there any other way I can create a Local Printer, Set the Driver, Port Number and Port Name and Share Name and Print Processor using vbscript in Windows 7???
Thank you in advance, the best response will receive points.
This is just what you need, for Windows 7:
The seven printer utilities, shown later, are located in the C:\Windows\System32\Printing_Admin_Scripts\en-US folder, which is not listed in the path. Therefore, you must actually change to this folder in order to run the utilities. And, since these utilities are designed to be run from the command line, you need to launch them from a Command Prompt window and run them using Windows Script Host's command-line-based script host (Cscript.exe).
Windows 7's VBScript printing utilities
VBScript File | What it does
---------------------------------------------
Prncnfg.vbs | Printer configuration
Prndrvr.vbs | Printer driver configuration
Prnjobs.vbs | Print job monitoring
Prnmngr.vbs | Printer management
Prnport.vbs | Printer port management
Prnqctl.vbs | Printer queue management
Pubprn.vbs | Publish a printer to Active Directory
Hope this works for you
I found another way to automate adding the printer, first I created a batch file then I used the prnmngr.vbs which comes with Windows 7 to automatically add the printer for me. For this to work I already had the Zebra driver installed on the machine (but the concept would be the same for any other type of printer). Then I ran the batch file.
Following shows how I did it, I've added the batch file text here:
Name the file: AddPrinter.bat
rem first change the directory to the script location
cd %WINDIR%\System32\Printing_Admin_Scripts\en-US\
rem vbs script path: %WINDIR%\System32\Printing_Admin_Scripts\en-US\Prnmngr.vbs
rem first add the port, specify name of port, assign it an IP Address, specify the type and the Port.
cscript prnport.vbs -a -r "LoopBack" -h 127.0.0.1 -o raw -n 9100
cscript prnport.vbs -a -r "LoopBack_2" -h 127.0.0.1 -o raw -n 9101
pause
rem specify the name of the new printer, specify the driver, specify the port it will use.
cscript prnmngr.vbs -a -p "VirtualPrinter" -m "ZDesigner LP 2844" -r "LoopBack"
pause
cscript prnmngr.vbs -a -p "Zebra LP2844" -m "ZDesigner LP 2844" -r "USB0001"
rem cscript prnmngr.vbs -a -p "Zebra GK420d" -m "ZDesigner GK420d" -r "LPT1:"
rem cscript prnmngr.vbs -a -p "Zebra GC420d" -m "ZDesigner GC420d" -r "COM1:"
pause
NET STOP SPOOLER
NET START SPOOLER
pause
To customise this you can use these websites as a reference;
http://technet.microsoft.com/en-us/library/cc725868(v=ws.10).aspx
http://technet.microsoft.com/en-us/library/bb490974.aspx
http://blog.ogwatermelon.com/?p=3489
http://winadminnotes.wordpress.com/2010/02/19/how-to-manage-printers-and-printer-drivers-remotely-from-command-line/
http://technet.microsoft.com/en-us/library/cc754352(v=ws.10).aspx

error handling in Vb script

I have a Vb script which calls a bat file.the bat file contans logic to send email.i run the bat file using objShell.run.when i give an invalid email server name in the bat file.the email is not sent.But objShell.run always returns a 0.How to do exception handling in this case.please help
If you are using the objShell.run method it is running a separately process and do not care about the current process you are running. I would look at the ProcessStartInfo. I think you can redirect the input/output/error stream from the ProcessStartInfo. Here and here are some link about it
Your best bet would be to use CDO to send your email right from the VBScript. Otherwise, error handling in Batch is extremely difficult and you will have to resort to exit codes.
If you want to send without installation then try the second method. you have to initialize the objects. In that example i remove h in the link because i can't post links
CDO.MESSAGE
'Script to send an email through QTP nice one Set oMessage = CreateObject("CDO.Message")
'==This section provides the configuration information for the remote SMTP server. '==Normally you will only change the server name or IP. oMessage.Configuration.Fields.Item _ ("ttp://schemas.microsoft.com/cdo/configuration/sendusing") = 2
'Name or IP of Remote SMTP Server oMessage.Configuration.Fields.Item _ ("ttp://schemas.microsoft.com/cdo/configuration/smtpserver") =""
'Server port (typically 25) oMessage.Configuration.Fields.Item _ ("ttp://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
oMessage.Configuration.Fields.Update oMessage.Subject = "Test Mail" oMessage.Sender = "" oMessage.To ="" 'oMessage.CC = "" 'oMessage.BCC = "" oMessage.TextBody = "Test Mail from QTP"&vbcrlf&"Regards,"&vbcrlf&"Test" oMessage.Send
Set oMessage = Nothing

Send mail from a Windows script

I would like to send mail from a script on a Windows Server 2003 Standard Edition. I think the server setup is pretty much out of the box.
The mail server is an Exchange one, and when you're on the internal network you can use plain old SMTP. I have done it from my machine with Perl, but unfortunately Perl is not available on the server.
Is there an easy way of doing this from a .bat-file or any other way that doesn't require installing some additional software?
Edit:
Thanks for the quick replies. The "blat" thingie would probably work fine but with wscript I don't have to use a separate binary.
I didn't see PhiLho's post the first time I edited and selected an answer. No need for me to duplicate the code here.
Just save the script to a file, say sendmail.vbs, and then call it from the command prompt like so:
wscript sendmail.vbs
It is possible with Wscript, using CDO:
Dim objMail
Set objMail = CreateObject("CDO.Message")
objMail.From = "Me <Me#Server.com>"
objMail.To = "You <You#AnotherServer.com>"
objMail.Subject = "That's a mail"
objMail.Textbody = "Hello World"
objMail.AddAttachment "C:\someFile.ext"
---8<----- You don't need this part if you have an active Outlook [Express] account -----
' Use an SMTP server
objMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
' Name or IP of Remote SMTP Server
objMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserver") = _
"smtp.server.com"
' Server port (typically 25)
objMail.Configuration.Fields.Item _
("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25
objMail.Configuration.Fields.Update
----- End of SMTP usage ----->8---
objMail.Send
Set objMail=Nothing
Wscript.Quit
Update: found more info there: VBScript To Send Email Using CDO
By default it seems it uses Outlook [Express], so it didn't worked on my computer but you can use a given SMTP server, which worked fine for me.
If the server happened (I realize how old this question is) to have Powershell v2 installed, the CmdLet Send-MailMessage would do this in one line.
Send-MailMessage [-To] <string[]> [-Subject] <string> -From <string> [[-Body] <string>] [[-SmtpServer] <string>] [-Attachments <string[]>] [-Bcc <string[]>] [-BodyAsHtml] [-Cc <string[]>] [-Credential <PSCredential>] [-DeliveryNotficationOption {None | OnSuccess | OnFailure | Delay | Never}] [-Encoding <Encoding>] [-Priority {Normal | Low | High}] [-UseSsl] [<CommonParameters>]
I don't know if dropping a binary alongside the .bat file counts as installing software, but, if not, you can use blat to do this.
If you have outlook/exchange installed you should be able to use CDONTs, just create a mail.vbs file and call it in a batch file like so (amusing they are in the same dir)
wscript mail.vbs
for the VBScript code check out
http://support.microsoft.com/kb/197920
http://www.w3schools.com/asp/asp_send_email.asp
forget the fact they the two links speak about ASP, it should work fine as a stand alone script with out iis.
I think that you'll have to install some ActiveX or other component what could be invoked from WScript, such as:
http://www.activexperts.com/ActivEmail/
and:
http://www.emailarchitect.net/webapp/SMTPCOM/developers/scripting.asp
Otherwise, you'll have to write the entire SMTP logic (if possible, not sure) in WScript all on your own.
Use CDONTS with Windows Scripting Host (WScript)
Is there a way you send without referencing the outside schema urls.
http://schemas.microsoft.com/cdo/configuration/
That is highly useless as it can't be assumed all boxes will have outside internet access to send mail internally on the local exchange. Is there a way to save the info from those urls locally?

Resources