如何在django中调用远程Fabric方法

Abh*_*bhi 1 python django fabric

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

def get_hostname(request):  
  hostname = os.system('fab remote_server hostname')  
  return hostname  
Run Code Online (Sandbox Code Playgroud)

whi*_*tmo 8

为了获得更好的控制和灵活性,您应该使用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')
Run Code Online (Sandbox Code Playgroud)