0

I'm trying to write a Python string (yaml) to /path/to/foo.yaml on a remote linux machine.

There's some fiddly Python/bash interop here.

My current solution looks like this:

ip = '1.2.3.4'
yaml = '...'

src = f'tmp-{i}.yaml'
dst = f'root@{ip}:/path/to/foo.yaml'

with open(src, 'w') as f:
    f.write(yaml)

cmd = f'scp -o StrictHostKeyChecking=no  -i mykey.pem  {src} {dst}'

subprocess.run(cmd.split())

So I'm writing to a temp-file, and then scp-ing that temp-file across using bash-in-Python.

Is there a more compact solution that avoids the temp-file creation?

WARNING: My solution is likely not resilient against filenames with spaces, so do not use blindly. If you are dealing with filenames with spaces, consider not doing that.

WARNING: google StrictHostKeyChecking if you use this code for anything that requires security

martineau
  • 119,623
  • 25
  • 170
  • 301
P i
  • 29,020
  • 36
  • 159
  • 267
  • https://superuser.com/questions/291829/how-do-i-scp-the-huge-output-of-a-command-directly-to-a-remote-machine – luk2302 Jan 19 '22 at 10:08
  • 3
    Does this answer your question? [In Python, how to write a string to a file on a remote machine?](https://stackoverflow.com/questions/19202314/in-python-how-to-write-a-string-to-a-file-on-a-remote-machine) – MYousefi Jan 19 '22 at 10:10

1 Answers1

0

Using Tempfile might make it a bit more straigtforward https://docs.python.org/3/library/tempfile.html#examples

And with the paramiko sshclient you can get rid of the bash/subprocess stuff https://www.tutorialspoint.com/How-to-copy-a-file-to-a-remote-server-in-Python-using-SCP-or-SSH

flexus
  • 465
  • 3
  • 9