如何使用fabric在没有本地临时文件的情况下获取远程文件的内容

问题描述 投票:0回答:4

我想使用 Fabric 获取远程文件的内容,而不创建临时文件。

python fabric
4个回答
26
投票
from StringIO import StringIO
from fabric.api import get

fd = StringIO()
get(remote_path, fd)
content=fd.getvalue()

13
投票

使用Python 3(和fabric3),我在使用

io.StringIO
时遇到这个致命错误:
string argument expected, got 'bytes'
,显然是因为Paramiko用字节写入类文件对象。所以我改用
io.BytesIO
并且它有效:

from io import BytesIO

def _read_file(file_path, encoding='utf-8'):
    io_obj = BytesIO()
    get(file_path, io_obj)
    return io_obj.getvalue().decode(encoding)

3
投票
import tempfile
from fabric.api import get
with tempfile.TemporaryFile() as fd:
    get(remote_path, fd)
    fd.seek(0)
    content=fd.read()

参见:http://docs.python.org/2/library/tempfile.html#tempfile.TemporaryFile

和:http://docs.fabfile.org/en/latest/api/core/operations.html#fabric.operations.get


0
投票

我也不想在本地存储临时文件,但有不同的方法。

Fabric 从较低层库公开安全文件传输协议 (SFTP) paramiko

遵循与本文相同的策略,我将 parimiko 换成了布料,并进行了一些返工。

class remote_operations:
  def __init__(self):
    pass

  def create_connection(self, hostname, username, kwarg_password):
    connection = fabric.connection.Connection(
      host=hostname, user=username,
      connect_kwargs=kwarg_password)
    return connection

  def open_remote_file(self, ssh_client:Connection, filename):
    sftp_client = ssh_client.sftp()
    file = sftp_client.open(filename)
    return file

并使用名为

values
的字典来使用它,其中包含我的主机、用户名和密码。

test = remote_operations()
client = test.create_connection(
    hostname=values.get('remote_host'),
    username=values.get('ssh_username'),
    kwarg_password={"password": values.get('ssh_password')})

file = test.open_remote_file(client, "/path/to/file.txt")

for line in file:
   print(line)

file.close()
client.close()
© www.soinside.com 2019 - 2024. All rights reserved.