Script to Download and Execute the bat file

I found this existing python script in the library that would really assist me with centralizing and executing bat file scripts to our end points.

The script downloads a .bat file off our our google drive public shared file link, downloads it to the specified folder and the executes it.

The link for the original article is below:

https://scripts.itarian.com/frontend/web/topic/script-to-download-and-execute-the-bat-file

However i have configured the procedure and run it, it does the following: Downloads the bat file to the specified folder but then modifies the bat file and infects a bunch of garbage into the bat file and thats it…

I am looking for it to download the batch file to the specified folder and then execute the bat file. My target end point is a windows server 2019 OS. The log file of the procedure shows the following:
C:\ProgramData\CSAutoMaintenance\CSTestBat\TestBat.bat C:\ProgramData\CSAutoMaintenance\CSTestBat\TestBat.bat Excuting Bat File --------------------------- C:\Program Files (x86)\COMODO\Comodo ITSM><!DOCTYPE html><html><head><meta name=“google” content=“notranslate”><meta http-equiv=“X-UA-Compatible” content=“IE=edge;”><style>@font-face{font-family:‘Roboto’;font-style:italic;font-weight:400;src:local(‘Roboto Italic’),local(‘Roboto-Italic’),url(//fonts.gstatic.com/s/roboto/v18/KFOkCnqEu92Fr1Mu51xIIzc.ttf)format(‘truetype’);}@font-face{font-family:‘Roboto’;font-style:normal;font-weight:300;src:local(‘Roboto Light’),local(‘Roboto-Light’),url(//fonts.gstatic.com/s/roboto/v18/KFOlCnqEu92Fr1MmSU5fBBc9.ttf)format(‘truetype’);}@font-face{font-family:‘Roboto’;font-style:normal;font-weight:400;src:local(‘Roboto Regular’),local(‘Roboto-Regular’),url(//fonts.gstatic.com/s/roboto/v18/KFOmCnqEu92Fr1Mu4mxP.ttf)format(‘truetype’);}@font-face{font-family:‘Roboto’;font-style:normal;font-weight:700;src:local(‘Roboto Bold’),local(‘Roboto-Bold’),url(//fonts.gstatic.com/s/roboto/v18/KFOlCnqEu92Fr1MmWUlfBBc9.ttf)format(‘truetype’);}</style><meta name=“referrer” content=“origin”><title>Infinitt_PACS_VR_SVR_Log_File_Recycling.bat - Google Drive</title><meta property=“og:title” content=“Infinitt_PACS_VR_SVR_Log_File_Recycling.bat”><meta property=“og:type” content=“article”><meta property=“og:site_name” content=“Google Docs”><meta property=“og:url” content=“https://drive.google.com/file/d/1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ/view?usp=drive_open&usp=embed_facebook”><link rel=“shortcut icon” href=“https://ssl.gstatic.com/docs/doclist/images/icon_14_generic_favicon.ico”><link rel=“stylesheet” href=“https://fonts.googleapis.com/css?family=Google+Sans:300,400,500,700”><link rel=“stylesheet” href=“https://www.gstatic.com//apps-fileview//ss/k=apps-fileview.v.8uYZcMJXS1k.L.X.O/d=0/ct=zgms/rs=AO0039vzgTbwksC4aREKTz3EpkiflBsJ1w”><script>_docs_flag_initialData={“docs-ails”:“docs_cold”,“docs-fwds”:“docs_sdf”,“docs-crs”:“docs_crs_nfd”,“docs-shdn”:0,“docs-tfh”:"",“info_params”:{},“docos-eddmh”:false,“docs-edcsp”:true,“docs-eohmo”:false,“uls”:"",“docs-enpf”:false,“docs-ce”:false,“docs-api-keys”:{},“buildLabel”:“texmex_2020.18-Thu_RC01”,“docs-show_debug_info”:false,“ondlburl”:“https://docs.google.com”,“drive_url”:“https://drive.google.com”,“app_url”:“https://drive.google.com/file/",“docs-mid”:2048,“docs-eicd”:false,“docs-icdmt”:[],“docs-sup”:"/file",“docs-seu”:“https://drive.google.com/file/d/1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ/edit”,“docs-crp”:"/file/d/1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ/view",“docs-crq”:“usp\u003ddrive_open”,“docs-ecvca”:true,“docs-uptc”:[“lsrp”,“ca”,“sh”,“noreplica”,“ouid”,“dl”,“hi”,“popr”,“sdsid”,“usp”,“urp”,“utm_source”,“utm_medium”,“utm_campaign”,“utm_term”,“utm_content”,“aaac”,“sle”],“docs-doddn”:"Continuum Systems”,“docs-dodn”:“continuum.za.com”,“docs-uddn”:"",“docs-udn”:"",“docs-cwsd”:"",“docs-gsmd”:"",“docs-epil”:false,“docs-esmp”:false,“docs-al”:[0,0,0,1,0],“docs-deculmu”:“https://support.google.com/drive?p\u003dsaving_errors",“docs-deuoflmu”:"",“docs-debulmu”:"",“docs-deodlmu”:"",“docs-ndt”:"Untitled Texmex”,“docs-prn”:"",“docs-emtbi”:false,“docs-as”:"",“docs-etdimo”:false,“docs-mdck”:"",“docs-etiff”:false,“docs-mriim”:1800000,“docs-eccbs”:false,“docos-sosj”:false,“docs-rlmp”:false,“docs-mmpt”:15000,“docs-erd”:false,“docs-erfar”:false,“docs-ensb”:false,“docs-ddts”:false,“docs-uootuns”:false,“docs-amawso”:false,“docs-mdso”:false,“docs-ofmpp”:false,“docs-anlpfdo”:false,“docs-phe”:"",“docs-pid”:"",“docs-ebbouf”:false,“docs-efs”:false,“docs-ricocpb”:false,“docs-eali”:false,“docs-etauihm”:false,“docs-eiap”:false,“docs-egs”:false,“docs-eeott”:false,“docs-eics”:false,“docos-plss”:false,“docs-hft”:"",“docs-edsi”:false,“docs-ececs”:false,“docs-eslars”:false,“docs-edp”:false,“docs-edlo”:false,“docs-eem”:false,“docs-offline-enccpd”:false,“docs-edsl”:false,“docs-efsii”:false,“docs-elcfd”:false,“docs-ejtlr”:false,“docs-edmitm”:false,“docs-enjec”:false,“docs-ehdr”:false,“docs-egmid”:false,“docs-efmsh”:false,“docs-elri”:true,“ecid”:true,“docs-eir”:false,“docs-edll”:false,“server_time_ms”:1589756305833,“gaia_session_id”:"",“app-bc”:"#d1d1d1",“enable_iframed_embed_api”:true,“docs-fut”:“https://drive.google.com#folders/{folderId}",“docs-isb”:false,“docs-enct”:false,“docs-agdc”:false,“docs-anddc”:false,“docs-adndldc”:false,“docs-efts”:false,“docs-cn”:"",“docs-dpftr”:false,“docs-dwc”:false,“docs-depquafr”:false,“docs-elsr”:false,“docs-elmc”:false,“docs-frbanmc”:false,“docs-rldce”:false,“docs-sasic”:false,“docs-dom”:false,“docs-ebidu”:false,“docs-edamc”:false,“docs-edomic”:false,“docs-eddm”:false,“docs-edpme”:"",“docs-fwd”:false,“docs-elds”:false,“docs-mcssa”:false,“docs-eph”:false,“docs-epat”:false,“docs-eppd”:false,“docs-essph”:false,“docs-tdd”:false,“docs-mib”:5242880,“docs-mip”:6250000,“docs-rsc”:"",“docs-ssi”:false,“docs-uoci”:"",“docs-gth”:"",“docs-po”:“https://drive.google.com”,“docs-to”:“https://drive.google.com”,“projector_view_url”:“https://drive.google.com/file/d/1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ/view?usp\u003ddocs_web”,“docs-seso”:false,“docs-eastdfm”:false,“docs-eastd”:false,“docs-eoes”:false,“docs-eoespr”:false,“docs-dpiuf”:false,“opendv”:false,“onePickImportDocumentUrl”:"",“opmbs”:5242880,“opmpd”:2500,“opbu”:“https://docs.google.com/picker”,“opru”:“https://drive.google.com/relay.html”,“opdu”:false,“opccp”:false,“ophi”:“texmex”,“opst”:“000770F2032503033543787FBFC5DC56B0F1F0E8E44B1F69F5::1589756305836”,“opuci”:"",“docs-eopiiv2”:true,“docs-dm”:“application/x-msdos-program”,“docs-ndsom”:[],“docs-sdsom”:[],“docs-lfui”:false,“jobset”:“prod”,“docs-etbws”:false,“docs-ebpi”:false,“docs-eebvt”:false,“docs-eebvf”:false,“docs-emsib”:false,“docs-eiib”:false,“docs-se”:false,“docs-egf”:false,“docs-surfb”:false,“docs-uptuf”:true,“docs-eodp”:false,“docs-odolh”:false,“docs-odpu”:[null,null,null,"//drive.google.com/odp/embed?authuser\u003d"],“docs-spdy”:false,“xdbcfAllowHostNamePrefix”:true,“xdbcfAllowXpc”:true,“docs-iror”:true,“promo_url”:"",“promo_second_url”:"",“promo_title”:"",“promo_title_prefix”:"",“promo_content_html”:"",“promo_more_element_text”:"",“promo_second_more_element_text”:"",“promo_element_id”:"",“promo_orientation”:1,“promo_arrow_alignment”:0,“promo_show_on_click”:false,“promo_hide_arrow”:false,“promo_show_on_load”:false,“promo_mark_dismissed_on_show”:false,“promo_use_global_preference”:false,“promo_use_material_styling”:false,“promo_close_button_text”:"",“promo_icon_url”:"",“promo_action_id”:"",“promo_impression_id”:0,“promo_is_contextual”:false,“docs-ccwt”:0,“docs-eccw”:false,“docs-epcc”:false,“docs_abuse_link”:“https://drive.google.com/abuse?id\u003d1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ”,“docs-msoil”:“docs_spanner”,“docs-gsoil”:“docs_gsabs”,"docs-fsd”:false}; _docs_flag_cek= null ;</script><script>window.viewerData = {config: {‘id’: ‘1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ’, ‘title’: ‘Infinitt_PACS_VR_SVR_Log_File_Recycling.bat’, ‘isItemTrashed’: false ,‘enableEmbedDialog’: true,‘projectorFeedbackId’: ‘99950’, ‘projectorFeedbackBucket’: ‘viewer-web’,}, configJson: ["",null,null,null,null,1,null,"",null,1,1,[1,null,null,“AIzaSyDVQw45DwoYh632gvsP5vPDqEKvb-Ywnb8”,0,null,1,null,null,“AIzaSyC1eQ1xj69IdTMeii5r7brs3R90eck-m7k”,0,"/drive/v2beta",0,0,1,[0,0,0]
After executing the Bat file it looks like something goes wrong in Comodo…and this output is then injected into my bat file that lands on my end point.

Please can you advise if there is a patch that is needed?

Thanks,
Herbert

Hi @herbert

Looks like it’s downloading some kind of HTML error page instead of the actual .bat file. Please, browse to the downloaded file, rename it from .bat to .html and open it with your web browser so you can see the actual output.

Please note that I’m not from Comodo, I’m just a fellow user who is intrigued by this error. :wink:

Regards,
– Javier Llorente
Endpoint Security - Devoteam

Hi @herbert

Looks like you are providing the link to the download page of the .bat file instead of the link to the file. Please note:

Link to the download page: https://drive.google.com/file/d/1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ/edit

Direct link to the file: https://drive.google.com/uc?export=download&id=1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ

Note that the File ID is the same, but the direct link to the file is slightly different. Please modify the script to use the direct link to the file and try again.

Let me know if this solves the reported issue. :slight_smile:

Regards,
– Javier Llorente
Endpoint Security - Devoteam

Hi Javier,

Thanks for your reply.

You have picked up on an interesting point, from my side i can very that the procedure i have configured definitely has the directo link to the file and NOT the link to the page.

I have attached a copy of the procedure in text file format for you to view, however on the 8th line you will find the code that has the direct link.

URL=r’https://drive.google.com/open?id=1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ’ # Provide the direct download link for the BAT file

So it seems like the file does get downloaded but gets edited by html code:

content=“Infinitt_PACS_VR_SVR_Log_File_Recycling.b at”><meta property=“og:type” content=“article”><meta property=“og:site_name” content=“Google Docs”><meta property=“og:url” content=“https://drive.google.com/file/d/1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ/view?usp=drive_open&usp=embed_facebook”>

How can a /view parameter inject html code into a .bat file? Perhaps this is Google sending back a /view parameter?

Could this be a google setting or is Comodo changing something after it executes the bat file?

C:\ProgramData\CSAutoMaintenance\CSTestBat\TestBat .bat C:\ProgramData\CSAutoMaintenance\CSTestBat\TestBat .bat Excuting Bat File --------------------------- C:\Program Files (x86)\COMODO\Comodo ITSM><!DOCTYPE html><html><head><meta name=“google”

Thanks,

download and execute bat file procedure text.txt (2.19 KB)

Hi Herbert,

The problem is that the URL you’re providing is not the direct download link for the .bat file, that link shows a webpage that asks for user interaction to download the file and, as the script cannot interact with the webpage, it just download that page. In this context, “direct download link” means a link that points directly to the file, without asking for any user interaction.

Please use the following link instead:


URL=r'https://drive.google.com/uc?export=download&id=1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ' # Provide the direct download link for the BAT file

Please note that the URL that allows the direct download uses the “export=download” parameter, instead of the “open” parameter that uses the URL that you’re currently using. Also note that when browsing to this URL, you’re directly prompted by the browser to download the file, instead of getting a webpage where you have to click to download it.

Using this link should solve your issue :slight_smile:

Regards,
– Javier Llorente
Endpoint Security - Devoteam

Hi Javier,

I understand exactly what you are saying.

I am using the direct link in my Itarian procedure:

URL=r’https://drive.google.com/uc?export=download&id=1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ’ Check my procedure attached to my previous comment. #To define a particular parameter, replace the ‘parameterName’ inside itsm.getParameter(‘parameterName’) with that parameter’s name

Folder_name=r"CSInfinittLogrecycle" # Give the new folder name
Folder_Path=r"C:\ProgramData\CSAutoMaintenance" # Provide Path for the New folder
URL=r’https://drive.google.com/open?id=1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ’ # Provide the direct download link for the BAT file
File_name=r"Infinitt_PACS_VR_SVR_Log_File_Recycling.bat" #Provide the Bat file name with extension
directory=Folder_Path+""+Folder_name

import os
import subprocess
import urllib
import ctypes

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

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)

def Download(src_path, URL,fp):
import urllib2

request = urllib2.Request(URL, headers={'User-Agent' : "Magic Browser"})
try:
    gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
    parsed = urllib2.urlopen(request,context=gcontext)
except:
    parsed = urllib2.urlopen(request)
if not os.path.exists(src_path):
    os.makedirs(src_path)
with open(fp, 'wb') as f:
    while True:
        chunk=parsed.read(100*1000*1000)
        if chunk:
            f.write(chunk)
        else:
            break
return fp

def bat(path):
print path
with disable_file_system_redirection():
print “Excuting Bat File”
process = subprocess.Popen([path],stdout=subprocess.PIPE)
stdout = process.communicate()[0]
print “---------------------------”
print stdout

if name==‘main’:
import time
fp = os.path.join(directory, File_name)
path=Download(directory, URL,fp)
print path
time.sleep(10)
bat(path)

Hi Javier,

Apologies i miss read your post.

I am trying your code now.

Will give you some feedback in due course.

Thanks,

Hi Herbert,

The procedure attached in your previous message still uses the wrong URL, please check line 5 and ensure you use the URL with the “export=download” parameter.

Regards,
– Javier Llorente
Endpoint Security - Devoteam

You are right!!

Face palm moment there!!

I am busy checking it, will come back to you soon.

Hi Javier,

The script is working very well now, I am able to run the procedure from the Itarian console and it does exactly what it needs to do. The file is copied down to the specified folder and then executed. As you correctly pointed out the issue here was that i needed to update the G-drive direct download path with the export=download parameter.

https://drive.google.com/uc?export=download&id=1PGtcEiilwobJ0elwCb0B1t_RK3PiaREQ I just wanted to add that after the procedure was corrected i then ran into some other issues not related to this procedure. The web browsers on the OS started to block the google drive direct link and flagged it as a non safe certificate…so to fix this i had to install a certificate exported from my firewall and imported into the browsers on the OS. After that our Fortigate Firewall started to block the google drive direct link as an unsafe / unauthorized download link, so i had to allow that through our internet policy. Once all of that was done the end result is that it is working really nicely. Thank you very much for assisting me on my query, this is a great community and impressive solution. Kind regards, Herbert

Hi @herbert

Thanks a lot for your detailed feedback, glad to help. :slight_smile:

A small addition: Google has a file size limit for direct downloads from Google Drive using the “export=download” parameter; I think that limit is 50MB but I’m not quite sure. As you might imagine, this size limit will not be an issue for downloading scripts and small programs, but it will become an issue if you need to deploy something larger, so just take it into account.

That’s all so far. Have a nice day!

– Javier Llorente
Endpoint Security - Devoteam

Hi Javier,

Thanks for the heads up.