Skip to main content
 首页 » 编程设计

python之如何在 Django 中调用远程结构方法

2025年05月04日10zhwl

我需要通过 django 在远程机器上调用一个 fabric 方法。我的意思是当用户发送给定请求时获取远程机器的主机名。 像这样:

def get_hostname(request):   
  hostname = os.system('fab remote_server hostname')   
  return hostname   

请您参考如下方法:

为了更好的控制和灵 active ,您应该使用 fabric 作为库。参见:http://docs.fabfile.org/en/1.3.3/usage/library.html

import fabric.api as fab 
from fabric.network import disconnect_all 
from contextlib import contextmanager 
 
@context_manager 
def ssh(settings): 
    with settings: 
         try: 
            yield 
         finally: 
            disconnect_all() 
 
def hostname(request, host='somehost', user='someuser', pw='secret'):   
    with ssh(fab.settings(host_string=host, user=user, password=pw)): 
         return fab.run('hostname')