1.根据字符串形式导入模块,并且找到其中的类并执行
import sys import os BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASEDIR) from conf import settings import importlib #用此模块 import requests server_info = {} for k,v in settings.PLUGIN_ITEMS.items(): #找到v字符串:src.plugins.nic.Nic,src.plugins.disk.Disk module_path,cls_name = v.rsplit('.',maxsplit=1) module = importlib.import_module(module_path) cls = getattr(module,cls_name) obj = cls() ret = obj.process() server_info[k] = ret requests.post(url=settings.API, data=server_info) #------------settings配置文件------------ PLUGIN_ITEMS = { 'nic':'src.plugins.nic.Nic', 'disk':'src.plugins.disk.Disk', } API = 'http://127.0.0.1:8000/api/server.html' #-----------src.plugins.nic.py 下的类---------- class Nic(object): def process(self): return 'nic info'
兼容性(三种方式)
#Agent【*】
#SSH【**Ansible或Fabric】
#SaltStack【***公司是有自动化工具】
代码示例:
# ---------------------1. agent形式 # import subprocess # result = subprocess.getoutput("命令") #---------------------- 2. SSH模式 # 192.168.16.72 一台虚拟机的信息 # root # redhat # 用户名和密码方式 # import paramiko #pip3 install paramiko # ssh = paramiko.SSHClient() # ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # ssh.connect(hostname='192.168.16.72', port=22, username='root', password='redhat') # stdin, stdout, stderr = ssh.exec_command('ifconfig') # result = stdout.read() # ssh.close() # print(result) # 公钥私钥方式 # import paramiko # private_key = paramiko.RSAKey.from_private_key_file('/home/auto/.ssh/id_rsa') # ssh = paramiko.SSHClient() # ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) # ssh.connect(hostname='c1.salt.com', port=22, username='wupeiqi', pkey=private_key) # stdin, stdout, stderr = ssh.exec_command('df') # result = stdout.read() # ssh.close() #-------------------- 3. SaltStack模式 # import subprocess # subprocess.getoutput('salt "c1.com" cmd.run "命令"')
补充 saltstack的安装:
1.执行命令:rpm --import https://repo.saltstack.com/yum/redhat/7/x86_64/latest/SALTSTACK-GPG-KEY.pub 2.在/etc/yum.repos.d/这个目录下创建一个文件:saltstack.repo touch saltstack.repo 3.在文件中粘贴下面的代码: [saltstack-repo] name=SaltStack repo for RHEL/CentOS $releasever baseurl=https://repo.saltstack.com/yum/redhat/$releasever/$basearch/latest enabled=1 gpgcheck=1 gpgkey=https://repo.saltstack.com/yum/redhat/$releasever/$basearch/latest/SALTSTACK-GPG-KEY.pub