自动化运维之Fabric系列(一)小试牛刀

十点数据 1年前 ⋅ 3201 阅读
最近开始对先前做的采集器进行升级,由于在其开发过程中,需要不断的对其进行测试。每次修改一个bug,或新增一个功能,都需要登录服务器、
上传文件、解压、重启服务等,非常繁琐。
今天开始使用Fabric来实现几个简单的、重复性的操作,如登录服务器、执行命令和上传文件。
废话不多说,上代码:
'''
Created on Jan 17, 2020
@author: admin
'''
from fabric import Connection
import traceback
class FabricUtils:
	def __init__(self, host:"服务器IP", userName:"用户名", password:"密码"):
    	self.host = host
    	self.userName = userName
    	self.password = password
    	print(self.userName + "@" + self.host, {"password": self.password})

    #初始化ssh链接对象;
    def initClient(self):
        self.con = Connection(self.userName + "@" + self.host, connect_kwargs={"password": self.password})
    
    #执行shell命令;
    def runCommand(self, sshCommand:"Linux命令行语句"):
        #top命令尚未测试通过;
        #如果命令行中包含路径,最好使用绝对路径;
        try:
            result = self.con.run(sshCommand, hide=True)
            if result.return_code == 0:# 返回码,0表示正确执行,1表示错误
                return True, result.stdout                         
            return result.failed, result.stdout
        except:
            exp = traceback.format_exc()
            if "Command: 'mkdir" in exp and 'File exists' in exp:
                print("目录【", sshCommand, "】已存在")
            else:
                print(exp)
            return False, exp
    #切换到某一目录
	def cd(self, dir):
    	return self.con.cd(dir) 
  
  	#上传文件
	def put(self, src:"待上传的文件全路径。路径中最好不要有空格等特殊字符", org:"保存到服务器上的目录"):
    	return self.con.put(src, org)
    
if __name__ == '__main__':
	fabricu = FabricUtils("服务器IP", "服务器登录用户名", "服务器登录密码")
	fabricu.initClient()
	print(fabricu.runCommand("tar -zxvf /home/Crawler/WeChatSouGouMain.tar.gz -C /home/Crawler/"))

上面代码尚存上下文无关的问题,如cd方法,执行后切换到某个目录下,但是如果再执行put方法上传文件。
如果org参数使用相对路径,则不是以切换后的目录为参照。如:
fabricu.cd("/home/crawler")
fabricu.runCommand("tar -zxvf /home/Crawler/WeChatSouGouMain.tar.gz -C ./")
执行完上述的两段代码以后,文件WeChatSouGouMain.tar.gz并不是上传到/home/crawler目录下,二十在当前用户的根目录下

全部评论: 0

    我有话说: