0

I'm trying to convert the following powershell script into a python script and I'm having trouble understanding the invoke-restmethod command and in particular, what to do with the -body parameter.

The powershell script is an example given to me by McAfee for how to upload a CSV file to their DLP platform. I've tried myself to do the conversion and I think I'm on the right lines but everything here is a guess based on previous code I've written in python and trying to figure out what the powershell command is doing. Any help to correct the below would be very much appreciated.

Here's the powershell example:

$username = "admin" 
$password = " PASSWORD123 " 
$password_base64 = ConvertTo-SecureString $password -AsPlainText -Force 
$creds = New-Object System.Management.Automation.PSCredential ($username, $password_base64) 


$fileName = ".\test.csv"
$uri = "https://epo:8443/rest/dlp/userInfo/import"

$currentPath = Convert-Path .
$filePath="$currentPath\$fileName"

$fileBin = [System.IO.File]::ReadAlltext($filePath)
$boundary = [System.Guid]::NewGuid().ToString()
$LF = "`r`n"
$bodyLines = ("--$boundary","Content-Disposition: form-data; name=`"importFile`"; filename=`"$fileName`"","Content-Type: application/octet-stream$LF",$fileBin,"--$boundary--$LF") -join $LF

Invoke-RestMethod -Uri $uri -Method Post -Credential $creds -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines 

And here's my attempt to convert it into python (as a test):

import requests
import base64

strUser = "admin"
strPW = "PASSWORD123"

strURL = ""https://epo:8443/rest/dlp/userInfo/import""

#base64encode the credentials
encodedBytes = base64.b64encode(str(strUser + ':' + strPW).encode("utf-8"))
encodedCredentials = str(encodedBytes, "utf-8")

headers_data = {'Content-Type': 'application/octet-stream',
               'cache-control': 'no-cache',
               'Authorization': encodedCredentials}

files = {
    'path': (None, 'importFile'),
    'filename': (None, 'C:\\test\\test file.csv')
}

with open('C:\\test\\test.csv', 'r') as reader:
    newContent = reader.read()

response = requests.post(strURL, headers=headers_data, data=newContent, files=files, verify=False)

Thank in advance

Paul
  • 13
  • 3

0 Answers0