Download web content through CMD - windows

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

Related

Email a batch variable to myself using batch script [duplicate]

I'm running Windows 2003 Service Pack 2. I have a batch file that runs on demand. I want to have an email sent every time the batch file runs. The email is simple, just a sentence indicating that the batch file ran; it is the same every time.
I've tried a couple of things to get this done. I thought of telnet, but I can't figure out how to redirect a set of commands into telnet; Windows batch files don't have a Unix-style "here document," and calling "telnet <scriptfile" where scriptfile contains the commands to send an email didn't work. I also found a couple of solutions on the internet using CDO.Message, but I've never used that before and I kept getting error messages that I don't understand.
How can I send a simple email from a Windows batch file?
Max is on he right track with the suggestion to use Windows Scripting for a way to do it without installing any additional executables on the machine. His code will work if you have the IIS SMTP service setup to forward outbound email using the "smart host" setting, or the machine also happens to be running Microsoft Exchange. Otherwise if this is not configured, you will find your emails just piling up in the message queue folder (\inetpub\mailroot\queue). So, unless you can configure this service, you also want to be able to specify the email server you want to use to send the message with. To do that, you can do something like this in your windows script file:
Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
'uncomment next three lines if you need to use SMTP Authorization
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Update
objMail.Configuration = objConf
objMail.FromName = "Your Name"
objMail.From = "your#address.com"
objMail.To = "destination#address.com"
objMail.Subject = "Email Subject Text"
objMail.TextBody = "The message of the email..."
objMail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing
I've used Blat ( http://www.blat.net/ ) for many years.
It's a simple command line utility that can send email from command line.
It's free and opensource.
You can use command like "Blat myfile.txt -to fee#fi.com -server smtp.domain.com -port 6000"
Here is some other software you can try to send email from command line (I've never used them):
http://caspian.dotconf.net/menu/Software/SendEmail/
http://www.petri.co.il/sendmail.htm
http://www.petri.co.il/software/mailsend105.zip
http://retired.beyondlogic.org/solutions/cmdlinemail/cmdlinemail.htm
Here ( http://www.petri.co.il/send_mail_from_script.htm ) you can find other various way of sending email from a VBS script, plus link to some of the mentioned software
The following VBScript code is taken from that page
Set objEmail = CreateObject("CDO.Message")
objEmail.From = "me#mydomain.com"
objEmail.To = "you#yourdomain.com"
objEmail.Subject = "Server is down!"
objEmail.Textbody = "Server100 is no longer accessible over the network."
objEmail.Send
Save the file as something.vbs
Set Msg = CreateObject("CDO.Message")
With Msg
.To = "you#yourdomain.com"
.From = "me#mydomain.com"
.Subject = "Hello"
.TextBody = "Just wanted to say hi."
.Send
End With
Save the file as something2.vbs
I think these VBS scripts use the windows default mail server, if present.
I've not tested these scripts...
If PowerShell is available, the Send-MailMessage commandlet is a single one-line command that could easily be called from a batch file to handle email notifications. Below is a sample of the line you would include in your batch file to call the PowerShell script (the %xVariable% is a variable you might want to pass from your batch file to the PowerShell script):
--[BATCH FILE]--
:: ...your code here...
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden -command C:\MyScripts\EmailScript.ps1 %xVariable%
Below is an example of what you might include in your PowerShell script (you must include the PARAM line as the first non-remark line in your script if you included passing the %xVariable% from your batch file:
--[POWERSHELL SCRIPT]--
Param([String]$xVariable)
# ...your code here...
$smtp = "smtp.[emaildomain].com"
$to = "[Send to email address]"
$from = "[From email address]"
$subject = "[Subject]"
$body = "[Text you want to include----the <br> is a line feed: <br> <br>]"
$body += "[This could be a second line of text]" + "<br> "
$attachment="[file name if you would like to include an attachment]"
send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Attachment $attachment -Priority high
If you can't follow Max's suggestion of installing Blat (or any other utility) on your server, then perhaps your server already has software installed that can send emails.
I know that both Oracle and SqlServer have the capability to send email. You might have to work with your DBA to get that feature enabled and/or get the privilege to use it. Of course I can see how that might present its own set of problems and red tape. Assuming you can access the feature, it is fairly simple to have a batch file login to a database and send mail.
A batch file can easily run a VBScript via CSCRIPT. A quick google search finds many links showing how to send email with VBScript. The first one I happened to look at was http://www.activexperts.com/activmonitor/windowsmanagement/adminscripts/enterprise/mail/. It looks straight forward.
$emailSmtpServerPort = "587"
$emailSmtpUser = "username"
$emailSmtpPass = 'password'
$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "[From email address]"
$emailMessage.To.Add( "[Send to email address]" )
$emailMessage.Subject = "Testing e-mail"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = #"
<p>Here is a message that is <strong>HTML formatted</strong>.</p>
<p>From your friendly neighborhood IT guy</p>
"#
$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );
$SMTPClient.Send( $emailMessage )
It works for me, by using double quotes around variables.
I am using batch script to call powershell Send-MailMessage
Batch Script:send_email.bat
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -command 'E:\path\send_email.ps1
Pwershell Script send_email.ps1
Send-MailMessage -From "noreply#$env:computername" -To '<target_email#example.com>' -Subject 'Blah Blah' -SmtpServer 'smtp.domain.com' -Attachments 'E:\path\file.log' -BODY "Blah Blah on Host: $env:computername "
I struggled with the same problem and finally found a simple soultion. I know I am late to answer this question. But still writing if it can help someone like me who is searching for it.
You can send simple mail using Powershell script. Make sure to connect this in your bat file
$Outlook = New-Object -ComObject Outlook.Application
$Mail = $Outlook.CreateItem(0)
$Mail.To = "hi#company.com"
$Mail.Subject = "hello"
$Mail.Body ="Hello. I am here to wish you"
$Mail.Send()
Using this, you need not use any other party apps or install anything extra. It just needs Outlook. I hope that will be already there in many office accounts.
This post helped me
Send E-Mail using powershell

Invoke web request based on system information

Ok so What I would like is a script that uses the invoke web request command based on a given system info.
So let's say i have two different installers one for a Nvidia gpu system and another for an AMD gpu system, I can already get the gpu info using another script, and save it to a html link or a text file, but how can I use this information, using invoke web request, to download the right installer?
This is the VB script I use to fetch the GPU info:
strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer &"\root\CIMV2")
Set colItems = objWMIService.ExecQuery( _ "SELECT *FROM Win32_VideoController",,48)
For Each objItem in colItems
Wscript.Echo "-----------------------------------"
Wscript.Echo "Win32_VideoController instance"
Wscript.Echo "-----------------------------------"
Wscript.Echo"Caption:"&objItem.Caption
Next
You don't need to mix-and-match VBS and PowerShell, PowerShell is perfectly capable of querying WMI on its own!
Use Where-Object to filter the results based on the Caption value, then use an if statement to determine whether any of each type was found:
$allVideoControllers = Get-CimInstance -Class Win32_VideoController
if($allVideoControllers |Where-Object Caption -like '*NVidia*'){
# Found an nvdia card, download and run the nvidia installer in here
}
if($allVideoControllers |Where-Object Caption -like '*AMD*'){
# Found an AMD card, download and run the AMD installer in here
}

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

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.

custom protocol handler via powershell script

QUESTION ANSWERED.. I have edited this question to the working solution.
Here's the scenerio.
Windows 10 workstation with Jitsi VOIP software installed.
I made a protocol handler for SIP: with this registry entry..
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\sip]
#="URL: SIP Protocol handler"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\sip\DefaultIcon]
#="C:\\Program Files (x86)\\Jitsi\\sc-logo.ico"
[HKEY_CLASSES_ROOT\sip\shell]
[HKEY_CLASSES_ROOT\sip\shell\open]
[HKEY_CLASSES_ROOT\sip\shell\open\command]
#="\"C:\\Program Files (x86)\\Jitsi\\Jitsi.exe\" %1"
This part works. Entering sip:1234567890 as a run command dials the number.
What I want to do is create a new protocol named CHK: that does a http request to a local webserver, and if the webserver
responds with 0, dial the number. If the response is 1, show a message "this number can't be dialed"
Here is the registry entry I made for this new chk protocol
Windows Registry Editor Version 5.00
[HKEY_CLASSES_ROOT\chk]
#="URL: CHK Protocol handler"
"URL Protocol"=""
[HKEY_CLASSES_ROOT\chk\DefaultIcon]
#="C:\\Program Files (x86)\\Jitsi\\sc-logo.ico"
[HKEY_CLASSES_ROOT\chk\shell]
[HKEY_CLASSES_ROOT\chk\shell\open]
[HKEY_CLASSES_ROOT\chk\shell\open\command]
#="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\"
-File C:\\DNC\\dnc.ps1 %1"
Even though this is nearly identical to SIP reg entry, when I try running chk:1234567890 I get an error "Apllication not found" , so
something is not right with the open comand....
edit: I was right, it was the open command.. I had the quotes in wrong place
and the content of the dnc.ps1 script...
$w=$args[0]
$chprot,$num = $w.split(':',2)
$url = "http://server/numchk.php?ph=$num"
$webclient = New-Object System.Net.WebClient
$webpage = $webclient.DownloadString($url)
if ($webpage -match "0"){
$launch = "C:\Program Files (x86)\Jitsi\Jitsi.exe"
$prot = 'sip:'
$arguments = $prot + $num
start-process $launch $arguments
} Else {
$wshell = New-Object -ComObject Wscript.Shell
$wshell.Popup("CANT DIAL $num ",0,"",0x0)
}
If I run the script via run command powershell -noexit -File c:\DNC\dnc.ps1 chk:1234567890
I can see the script is doing the right thing, dialing numbers if response is zero, show can't dial message if response is 1.
Again.. I think the problem is with the registry entry... specifilly the command/open part...
[HKEY_CLASSES_ROOT\chk\shell\open\command]
#="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe -File C:\\DNC\\dnc.ps1\" %1"
Some trick to passing an argument to an argument I am missing :(
I think you have a quote in the wrong place, so it's not looking for "powershell.exe", it's looking for a file named "powershell.exe -File C:\DNC\dnc.ps1".
Does this work?
[HKEY_CLASSES_ROOT\chk\shell\open\command]
#="\"C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\powershell.exe\" -File C:\\DNC\\dnc.ps1 %1"

compiling less to css from classic asp / vbscript

I'm trying to get classic asp / vbscript to run a less compiler (https://github.com/duncansmart/less.js-windows). Running the exact command from a real cmd prompt on the server works fine. So it's going to be one of those permissiony type things. My server is Win2003 x86 / IIS6.
<%
' foo.asp
outpath = "c:\inetpub\wwwroot\site\less"
cmd = "c:\less.js-windows-v1.6.2\lessc.cmd"
Set Shell = server.createobject("WScript.Shell")
nodeCommand = cmd & " " & outPath & "\app.less " & outPath & "\app.css"
errCode = Shell.Run(nodeCommand, 0, True)
' errcode = 1
%>
foo.asp is running somewhere on the web server, anonymously.
cmd.exe has had iusr_server added so that it has read and execute permission.
c:\less.js-windows-v1.6.2 has had iusr_server added with read/execute as well.
I've granted everyone permission to modify files in side c:\inetpub\wwwroot\site\less to make sure it's not a permission thing.
I have tried modifying my command to include CMD /C ahead of the command file name.
Use the following process:
Stop the server
Change relative paths to full paths for all files
Reconfigure the IUSR to be you
Restart the server

Resources