Download File

Please use the script to download a file from specific URL to specific Folder

import urllib
import os

def downloadFile(DownTo, fromURL):
    try:
        fileName = fromURL.split('/')[-1]
        DownTo = os.path.join(DownTo, fileName)
        with open(DownTo, 'wb') as f:
            f.write(urllib.urlopen(fromURL).read())
        if os.path.isfile(DownTo):
            return '{} - {}KB'.format(DownTo, os.path.getsize(DownTo)/1000)
    except:
        return 'Please Check URL or Download Path!'

if __name__=='__main__':
    print downloadFile('C:\\Users\\Prime\\Downloads', 'http://download.piriform.com/ccsetup523.exe')

Sample Output:

Download File.PNG

Hooray, this is just what I was hoping to find. Unfortunately, after customizing the script, I encountered the built-in error as the results… “Please check URL or Download Path!”

I went back and copied your example exactly and still get the same error.

Any recommendations would be appreciated.

Hi @taber

Refer procedure line

print downloadFile(‘C:\Users\Prime\Downloads’, ‘http://download.piriform.com/ccsetup523.exe’)

Please replace “Prime” with your user account name in C:\Users\Prime\Downloads . if this still not resolve your problem , kindly share your URL link and Username to us. We will make it work for you.

Would it be possible to include a check that the download folder exists before starting the script? If it doesnt exist can it be created? Id like to use this to download a file in to a temp folder on the root of the C drive.

Would also be good to have a single script to just create a folder. That way the procedures could be linked.

Hi @Joners

It’s possible, we will get back to you within 30 minutes.
Thank you.

Hi @Joners

Please use this script to create a folder if it not exists :


import os

DownTo=os.environ['Temp']+r'\Downloads'
if not os.path.exists(DownTo):
    os.makedirs(DownTo)

Hi @Joners

This Script will allow you to Download file in specified path Eg:" ProgramaData\c1_temp\Downloads " because writing files in Temp folder may cause error. So, kindly please refer this Script


DownTo=r"<U+202A>C:\ProgramaData\c1_temp\Downloads" #Give your path here other than temp
URL='http://download.piriform.com/ccsetup523.exe'   #Give url To download

import urllib
import os


if not os.path.exists(DownTo):
    os.makedirs(DownTo)


def downloadFile(DownTo, fromURL):
    try:
        fileName = fromURL.split('/')[-1]
        DownTo = os.path.join(DownTo, fileName)
        with open(DownTo, 'wb') as f:
            f.write(urllib.urlopen(fromURL).read())
        if os.path.isfile(DownTo):
            return '{} - {}KB'.format(DownTo, os.path.getsize(DownTo)/1000)
    except:
        return 'Please Check URL or Download Path!'

print downloadFile(DownTo, URL)



Im afraid that this doesnt work for me.

should it be URL or fromURL? It seems to differ in places. Also it reports a success when nothing happens. Ive also found that it can fail on trying to create a new directory. Does this support downloading files from https sites?

Hi @Joners

Yes, it supports downloading files from HTTPS sites.
It should be URL only, before giving URL ensure that the URL is working, means directly downloading the file.
Could you please tell me the path where you wanted to create Directory ?

Hi Joners

This will definitely work. We are assigning URL value back to fromURL. ‘Finished success’ is your procedure ran status and we are printing ‘Please check URL or Download path’ if download not success in the execution logs.

This script support downloading files from https sites as well.

Thanks
Kannan

Hi,

Ive tried several different folder locations, the default that you have in there, with the folder existing and without. Ive created new folders there and have left them. Also created a c: est folder on the root of the C drive and another on to a users desktop with no joy.

The file im downloading is a 2Gb zip from a digital ocean space (which is the same as S3). The link works fine if downloading via a browser.

Ive had it report successful multiple times and there are no files there.

thanks!

Hi @Joners

Could you please provide us the link you tried to download and i damn sure creating directory is working perfectly from our side, Let me check again hope will reach you with better things.

Thank you.

Hi @Joners

Please refer this script it works perfect. Hope you will get satisfied with this.

path=r'C:\sss' #Give the path where you want to save
URL=r'http://download.piriform.com/ccsetup523.exe' #Give the download URL

def Download(path, URL):
    import urllib2
    import os
    print "Download started"
    fileName = URL.split('/')[-1]
    fp = os.path.join(path, fileName)
    request = urllib2.Request(URL, headers={'User-Agent' : "Magic Browser"})
    parsed = urllib2.urlopen(request)
    if os.path.exists(path):
        print "Path already exists"
    if not os.path.exists(path):
        os.makedirs(path)
        print "Path created"
    with open(fp, 'wb') as f:
        while True:
            chunk=parsed.read(100*1000*1000)
            if chunk:
                f.write(chunk)
            else:
                break
    print "The file downloaded successfully in specified path"
    print fp

Download(path, URL)

@Aravind_pandi Now how about another one? Would it be possible to write a script that uses uses BITS to download a file… but… use BITS ability to throttle the download speed to xx mbps?

thanks!

@Joners

Do you want a script to show the downloading BITS speed ? or want to control BITS speed to the specified xx mbps ?

@Joners

It’s possible, will reach you shortly with good result.

Thank you

@Joners

This script will allow you to Download a file using BITS and allow to control the Download Speed limit.

NOTE:

  • value="2000" # Give the value of control speed in kbps.
  • path="C:\ProgramData" # Give the path where want to save the downloaded file.

Output screen will have the job details done with BITS process.


value="2000"  # Give the value of control speed. NOTE: It's in kbps.
path="C:\ProgramData" # Give the path where want to save the downloaded file.

def Registry_change():
    script=r"""
               Const HKEY_LOCAL_MACHINE = &H80000002
    strComputer = "."
    Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
    strComputer & "\root\default:StdRegProv")

    strKeyPath = "SOFTWARE\Policies\Microsoft\Windows\BITS"
    oReg.CreateKey HKEY_LOCAL_MACHINE,strKeyPath
    strValueName1 = "EnableBITSMaxBandwidth"
    strValueName2 = "MaxBandwidthValidFrom"
    strValueName3 = "MaxBandwidthValidTo"
    strValueName4 = "MaxTransferRateOffSchedule"
    strValueName5 = "MaxTransferRateOnSchedule"
    strValueName6 = "UseSystemMaximum"
    'Enabled
    dwValue1 = 1
    dwValue2 = 8
    dwValue3 = 17
    dwValue4 = %s
    dwValue5 = 10
    dwValue6 = 1
    oReg.SetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName1,dwValue1
    oReg.SetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName2,dwValue2
    oReg.SetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName3,dwValue3
    oReg.SetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName4,dwValue4
    oReg.SetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName5,dwValue5
    oReg.SetDWORDValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName6,dwValue6

        }"""%(value)

    import ctypes
    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)
    with disable_file_system_redirection():
            import os
            path =os.environ['TEMP']
            file = path+'\\'+'Registry_change.vbs'
            fobj= open(file, "w");
            fwrite=fobj.write(script);
            fobj.close();
            run=os.popen('cscript.exe '+file).read();
            print 'Enabled BITS background transfering Process , Speed is Limited with Specified Value.
'
            print 'Download Started to the Specified path
'
            try:
                os.remove(file)
            except OSError:
                pass
    return

Registry_change()
percentage="%"
ps_content=r'''
Import-Module BitsTransfer
$file ="http://ftp.belnet.be/mirror/videolan/vlc/2.2.6/win32/vlc-2.2.6-win32.exe"
$path="%s"
$bitsjob = Start-BitsTransfer -Source $file -Destination $path -Asynchronous
while( ($bitsjob.JobState.ToString() -eq 'Transferring') -or ($bitsjob.JobState.ToString() -eq 'Connecting') )
{
$Proc = ($bitsjob.BytesTransferred / $bitsjob.BytesTotal) * 100
}
Get-BitsTransfer
Get-BitsTransfer | Complete-BitsTransfer

Write-Host "Download Completed `n";

Write-Host "Job Details : `n";
'''%(path)

file_name='bits.ps1' # define your own file name

import os

def ecmd(command):
    import ctypes
    from subprocess import PIPE, Popen

    class disable_file_system_redirection:
        _disable = ctypes.windll.kernel32.Wow64DisableWow64FsRedirection
        _revert = ctypes.windll.kernel32.Wow64RevertWow64FsRedirection
        def __enter__(self):
            self.old_value = ctypes.c_long()
            self.success = self._disable(ctypes.byref(self.old_value))
        def __exit__(self, type, value, traceback):
            if self.success:
                self._revert(self.old_value)

    with disable_file_system_redirection():
        obj = Popen(command, shell = True, stdout = PIPE, stderr = PIPE)
        out, err = obj.communicate()
        ret=obj.returncode
        if ret==0:
            if out:
                return out.strip()
            else:
                return ret
        else:
            if err:
                return err.strip()
            else:
                return ret

file_path=os.path.join(os.environ['TEMP'], file_name)
with open(file_path, 'wb') as wr:
    wr.write(ps_content)

ecmd('powershell "Set-ExecutionPolicy RemoteSigned"')
print ecmd('powershell "%s"'%file_path)




Thanks,
Aravind