python fabric 编写SSH 连接类


#-*- coding:utf8 -*-
from fabric import Connection

class linuxOper(object):
    def __init__(self,ipaddr,user='root',password='',port=22,gateway=''):
        self.gateway = gateway
        if self.gateway:
            self.connobj = Connection(host=ipaddr,
                                  user=user,connect_kwargs={'password':password},port=int(port),gateway=self.gateway,)
        else:
            self.connobj = Connection(host=ipaddr, port=int(port),
                                 user=user, connect_kwargs={'password': password},)
    def getConnObj(self):
        return self.connobj
    def run(self,cmd):
        return self.connobj.run(cmd).stdout

if __name__ == '__main__':
    # 普通模式
    lsobj = linuxOper('192.168.2.1','root','qqq')
    # 执行命令
    lsobj.run('ls -l')
    
    # 中继模式
    newsobj = linuxOper('192.168.1.10','root','qqq',gateway=lsobj.getConnObj())
    # 执行命令
    newsobj.run('ls -l')


猜你喜欢

转载自blog.51cto.com/5766902/2286761
今日推荐