Write a local string to a remote file using python paramiko

user2451085 picture user2451085 · Jun 4, 2013 · Viewed 9.9k times · Source

I need to write a string to a file on a remote host using python's paramiko module. I've been trialing various methods of redirecting input but with no success.

The localstring in the below code snippet is populated with the result of a cat command

stdin, stdout, stderr = hydra.exec_command('cat /file.txt')
localstring = stdout.read()
manipulate(localstring)
hydra.exec_command('cat > newfile.txt\n' + localstring + '\n')

I seem to have my script hang or receive an EOF error or not have the resulting string appear in the file at all. Note that the file has multiple lines.

Answer

Nigel picture Nigel · Dec 5, 2015

You could also use the ftp capability:

import paramiko

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect('example.com', username='username', password='password')

ftp = ssh.open_sftp()
file=ftp.file('remote file name', "a", -1)
file.write('Hello World!\n')
file.flush()
ftp.close()
ssh.close()