2017-05-19 4 views
2

Paramiko를 현재 사용하고있는 많은 스크립트에 대한 SSH 클라이언트로 대체하는 방법을 생각해 내고 있습니다. 지금까지 테스트를 위해이 초안을 생각해 냈습니다. :Python SSH : paramiko의 대안으로 fabric.api 사용

ssh_handler.py

import sys 
from fabric.api import run 
from fabric.api import task 
from fabric.api import execute 
from fabric.network import disconnect_all 


def worker(command): 
    run(command) 


@task 
def cmd(host, command): 

    host_list = list() 

    if isinstance(host, (str, unicode)): 
     host_list.append(host) 

    elif isinstance(host, list): 
     host_list += host 

    else: 
     sys.exit(1) 

    # run the command 
    execute(worker(command), hosts=host_list) 

    # disconnect 
    disconnect_all() 

    return 

다른 스크립트에서이 작업을 실행할 때의 말을하자

testing.py

,
import ssh_handler 


node_list = ["192.168.0.1", "192.168.0.2"] 

for node in node_list: 
    ssh_handler.cmd(node, "uptime") 

결과 :

./testing.py 
No hosts found. Please specify (single) host string for connection: ^C 

이 사람이 올바른 방향으로 날 지점 수 있을까요? 이유는 무엇입니까 fabric.api.execute호스트 매개 변수를 실행하는 동안 인식 할 수 없습니까?


대답 :이 작업을 수행하여 문제를 해결할 수 있었다

:

import sys 
from fabric.api import run 
from fabric.tasks import execute 
from fabric.network import disconnect_all 


class FabricHelper: 
    def __init__(self): 
     self.host_list = list() 
     pass 

    def set_hosts(self, host): 

     if isinstance(host, (str, unicode)): 
      self.host_list.append(host) 
     elif isinstance(host, list): 
      self.host_list += host 
     else: 
      sys.exit(1) 
     return 

    def cmd(self, command): 
     execute(run, command=command, hosts=self.host_list) 
     disconnect_all() 
     return 


if __name__ == "__main__": 

    example = FabricHelper() 
    example.set_hosts(["10.200.10.51", "10.200.10.52"]) 
    example.cmd("uptime") 

답변

0

난 당신의 코드에 의해 혼란 비트, execute는 일반적으로 작업을 실행하는 데 사용됩니다입니다. 그러나 worker은 작업이 아닙니다. 작업자는 실행 호출에 대한 호출 인 하나의 라이너 일뿐입니다. 그래서 그것은 내게 나타납니다 worker 삭제할 수 있습니다.

처음에 나는이 테스트 프레임 워크가 여러분이 사용하고있는 것이 무엇인지 궁금해했습니다. 그렇다면 test라는 또 다른 파이썬 파일이라는 것을 깨달았습니다!

마지막으로 이러한 모든 정교한 메커니즘 대신, env dictionary에 호스트를 설정하는 것이 가장 좋은 이유는 무엇입니까?