Receiver = itsm.getParameter('EmailTo')  ## Provide an Toemail address where the mail need to be sent.You can also provide any number of To eamil address For example: ['varun@yopmail.com', xxxx@yopmail.com]
Sender = itsm.getParameter('EmailFrom')  ## Provide the From Email address from which the mail to be send
Password = itsm.getParameter('Password')               ##Provide password for from email
onedrive_admin_account = itsm.getParameter('Onedrive_admin_account') #prvide your onedrive admin account id here
onedrive_account_password = itsm.getParameter('Onedrive_account_password') #provide your onedrive account password
onedrive_url = itsm.getParameter('Onedrive_url') #provide your onedrive url
Drive = ["C:","D:"] #provide the disk names you want to encrypt
save = "C:"

import os
import subprocess
import ctypes
import re
import urllib 
import smtplib
import mimetypes
import socket
import ssl 
from email.mime.multipart import MIMEMultipart
from email import encoders
from email.message import Message
from email.mime.audio import MIMEAudio
from email.mime.base import MIMEBase
from email.mime.image import MIMEImage
from email.mime.text import MIMEText

content = r'''$User = %s%s%s
$SiteURL = %s%s%s


$Folder = "C:\Recoverykey"
$DocLibName = "Documents"

#Add references to SharePoint client assemblies and authenticate to Office 365 site – required for CSOM
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"


$Password  = ConvertTo-SecureString %s%s%s -AsPlainText -Force


#Bind to site collection
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($User,$Password)


$Context.Credentials = $Creds

#Retrieve list
$List = $Context.Web.Lists.GetByTitle("$DocLibName")


$Context.Load($List)



$Context.ExecuteQuery()

#Upload file
Foreach ($File in (dir $Folder -File))
{
$FileStream = New-Object IO.FileStream($File.FullName,[System.IO.FileMode]::Open)
$FileCreationInfo = New-Object Microsoft.SharePoint.Client.FileCreationInformation
$FileCreationInfo.Overwrite = $true
$FileCreationInfo.ContentStream = $FileStream
$FileCreationInfo.URL = $File
$Upload = $List.RootFolder.Files.Add($FileCreationInfo)
$Context.Load($Upload)
$Context.ExecuteQuery()
}'''%('"',str(onedrive_admin_account),'"','"',str(onedrive_url),'"','"',str(onedrive_account_password),'"')
cp_name = os.environ['COMPUTERNAME']
ip = socket.gethostbyname(socket.gethostname())
if not os.path.exists(os.path.join(save+r"\\Recoverykey")):
    os.makedirs(os.path.join(save+r"\\Recoverykey"))
else:
    pass 
fp=os.path.join("C:\\Recoverykey\\Recoverykey.txt")

def onedrive(file):
    url_64 = "https://script-downloads.comodo.com/sharepoint/sharepointclientcomponents_64.msi"
    url_32 = "https://script-downloads.comodo.com/sharepoint/sharepointclientcomponents_86.msi"
    if os.path.exists("C:\\Program Files\\Common Files\\Microsoft Shared\\Web Server Extensions\\15\ISAPI"):
        pass 
    else:
        obj=subprocess.Popen("wmic os get osarchitecture",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        result,error=obj.communicate()
        if error:
            print(error)
        else:
            operating_system = result.split()

        if '64-bit' in operating_system :
            destination = "C:\\sharepoint_64.msi"
            gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            download = urllib.urlretrieve(url_64,destination,context = gcontext)
            save_path = 'C:\\'
            file_name = "sharepoint.bat"
            completeName = os.path.join(save_path, file_name)
            file1 = open(completeName, "w+")
            file1.write('''@echo off
                        msiexec /i C:\\sharepoint_64.msi /quiet /qn /log c:\users\install.log
                        ''')
            file1.close()
            cmd = subprocess.Popen(completeName,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            result_1,error_1=cmd.communicate()
            if error_1:
                print(error_1)
            else:
                pass 
        else:
            destination = "C:\\sharepoint_32.msi"
            gcontext = ssl.SSLContext(ssl.PROTOCOL_TLSv1)
            download = urllib.urlretrieve(url_32,destination,context = gcontext)
            save_path = 'C:\\'
            file_name = "sharepoint.bat"
            completeName = os.path.join(save_path, file_name)
            file1 = open(completeName, "w+")
            file1.write('''@echo off
                        C:\\Recoverykey\\sharepoint_32.msi /quiet /qn /log c:\users\install.log
                        ''')
            file1.close()
            cmd = subprocess.Popen(completeName,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
            result_2,error_2=cmd.communicate()
            if error_2:
                print(error_2)
            else:
                pass 
    cmd = subprocess.Popen(["powershell","Set-ExecutionPolicy RemoteSigned"],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
    result,error=cmd.communicate()
    if error:
        print(error)
    else:
        cmd_1 = subprocess.Popen(["powershell",file],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        result_1,error_1=cmd_1.communicate()
        if error_1:
            print(error_1)
        else:
            print ("Recovery key uploaded to onedrive account "+onedrive_admin_account)


def gmail(sender_email,password,receiver,file):
    fileToSend = file 
    msg = MIMEMultipart()
    msg["From"] = sender_email
    msg["To"] = receiver
    msg["Subject"] = "Recovery key file attached"
    
    ctype, encoding = mimetypes.guess_type(fileToSend)
    if ctype is None or encoding is not None:
        ctype = "application/octet-stream"

    maintype, subtype = ctype.split("/", 1)

    if maintype == "text":
        cp = open(fileToSend)
        # Note: we should handle calculating the charset
        attachment = MIMEText(cp.read(), _subtype=subtype)
        cp.close()
    elif maintype == "image":
        cp = open(fileToSend, "rb")
        attachment = MIMEImage(cp.read(), _subtype=subtype)
        cp.close()
    elif maintype == "audio":
        cp = open(fileToSend, "rb")
        attachment = MIMEAudio(cp.read(), _subtype=subtype)
        cp.close()
    else:
        cp = open(fileToSend, "rb")
        attachment = MIMEBase(maintype, subtype)
        attachment.set_payload(cp.read())
        cp.close()
        encoders.encode_base64(attachment)
    attachment.add_header("Content-Disposition", "attachment", filename=fileToSend)
    msg.attach(attachment)
    server = smtplib.SMTP("smtp.gmail.com:587")
    server.starttls()
    server.login(sender_email,password)
    server.sendmail(sender_email, receiver, msg.as_string())
    server.quit()

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():
    for drive in Drive:
        path = 'C:\\Windows\\System32\\manage-bde.exe -status '+drive
        cmd = subprocess.Popen(path,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
        res, err = cmd.communicate()
        if err:
            print err 
        else:
            protect = re.findall("Lock Status:          (.*)",res)
            sta = re.findall("Conversion Status:    (.*)",res)
            pro="".join(protect)
            status = "".join(sta) 
            if "Unlocked" in pro and "Fully Decrypted" in status:
                print "Disk "+drive+" is now in locked state"
                cmd_1 = subprocess.Popen('manage-bde -on '+drive+' -RecoveryKey '+save+' -RecoveryPassword',shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
                res_1, err_1 = cmd_1.communicate()
                if err_1:
                    print err_1
                else:
                    keyword = "ACTIONS REQUIRED:"
                    before_keyword, keyword, after_keyword = res_1.partition(keyword)
                    recovery_key = (after_keyword.strip().splitlines()[3])
                    print("Encryption is now in progress for Disk"+" "+drive)
                    if os.path.exists(fp):
                        with open(fp,"a") as f:
                            f.write("Recovery Password for Disk "+drive+"  ")
                            f.write(recovery_key+"\n")
                            f.close()
                    else:
                        with open (fp,"w") as f:
                            f.write("Computer Name : "+cp_name+"\n")
                            f.write("IP-Address : "+ip +"\n")
                            f.write("Recovery Password for Disk "+drive+"  ")
                            f.write(recovery_key+"\n")
                            f.close()
            else:
                print("Disk "+drive+" already Encrypted")
    if os.path.exists(fp):
        gmail(Sender,Password,Receiver,fp)
        print("Recovery key emailed to "+Receiver)
        file_path="C:\\powershell_file.ps1"
        with open(file_path, 'wb') as wr:
            wr.write(content)
        onedrive(file_path)
        os.remove(file_path)
    else:
        pass 