Skip to content

Instantly share code, notes, and snippets.

@utkonos
Created July 11, 2022 00:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save utkonos/b8800b70f09d0eca46f3993fb437f904 to your computer and use it in GitHub Desktop.
Save utkonos/b8800b70f09d0eca46f3993fb437f904 to your computer and use it in GitHub Desktop.
Send File via WinRM
import hashlib
import base64
import pathlib
import tqdm.auto
import winrm
def send_file(s, source, destination):
"""Send file to remote location in base64 encoded chunks via WinRM."""
chunk_size = 2048
write_chunk = "[Byte[]]$to_write = [System.Convert]::FromBase64String('{}')\n$to_write | Add-Content -Encoding Byte {}"
with tqdm.auto.tqdm(total=source.stat().st_size) as t, with source.open('rb') as fh:
while chunk := fh.read(chunk_size):
encoded = base64.standard_b64encode(chunk).decode()
command = write_chunk.format(encoded, destination)
result = s.run_ps(command)
if result.status_code:
break
t.update(chunk_size)
if 'Completed' not in result.std_err.decode():
raise RuntimeError(f'File send failed: {source.name}')
get_sha256 = 'Get-FileHash {} -Algorithm SHA256 | ConvertTo-Json'
command = get_sha256.format(destination)
result = s.run_ps(command)
if result.status_code:
raise RuntimeError(f'Remote hash calculation failed: {source.name}')
data = json.loads(result.std_out)
sha256_remote = data.get('Hash').lower()
file_data = source.read_bytes()
sha256_local = hashlib.sha256(file_data).hexdigest().lower()
if sha256_remote != sha256_local:
raise RuntimeError(f'Hash mismatch: {source.name}')
s = winrm.Session('192.0.2.1', auth=('Administrator', 'password'))
source = pathlib.Path('test.dat')
destination = f'C:\{source.name}'
send_file(s, source, destination)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment