在Python中,如何将字符串写入远程计算机上的文件?

2024-04-18 21:04:03 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

如果你只想调用一个子进程,也许sh.py 可能是对的。

from sh import ssh
remote_host = ssh.bake(<remote host>) 
remote_host.dd(_in = <your binary string>, of=<output filename on remote host>) 

使用subprocess.Popen打开到Machine2的新SSH进程,然后将数据写入其STDIN。

import subprocess

cmd = ['ssh', 'user@machine2',
       'mkdir -p output/dir; cat - > output/dir/file.dat']

p = subprocess.Popen(cmd, stdin=subprocess.PIPE)

your_inmem_data = 'foobarbaz\0' * 1024 * 1024

for chunk_ix in range(0, len(your_inmem_data), 1024):
    chunk = your_inmem_data[chunk_ix:chunk_ix + 1024]
    p.stdin.write(chunk)

我刚刚验证了它的工作原理,并复制了10485760个伪字节。

p.S.一个可能更干净/更优雅的解决方案是让Python程序将其输出写入sys.stdout,然后在外部执行管道操作ssh

$ python process.py | ssh <the same ssh command>

Paramiko支持在远程计算机上打开文件:

import paramiko

def put_file(machinename, username, dirname, filename, data):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(machinename, username=username)
    sftp = ssh.open_sftp()
    try:
        sftp.mkdir(dirname)
    except IOError:
        pass
    f = sftp.open(dirname + '/' + filename, 'w')
    f.write(data)
    f.close()
    ssh.close()


data = 'This is arbitrary data\n'.encode('ascii')
put_file('v13', 'rob', '/tmp/dir', 'file.bin', data)

相关问题 更多 >