private_key = paramiko.RSAKey.from_private_key_file('c:/Users/用户名/.ssh/id_rsa')
# 创建ssh对象
ssh = paramiko.SSHClient()
# 运行连接不在know_host文件中的主机
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接服务器
ssh.connect(hostname='主机名', port='端口号', username='用户名', pkey=private_key)
# 执行命令
stdin, stdout, stderr = ssh.exec_command("命令")
# 获取结果
result = stdout.read()
# 关闭连接
ssh.close()
from concurrent.futures import ThreadPoolExecutor
# 创建一个十个线程的线程池
def task(i):
print("我是任务%s" % i)
pool = ThreadPoolExecutor(10)
for i in range(10):
pool.submit(task,i)
import logging
import traceback
# import settings
class Logger(object):
def __init__(self, file_path, level):
file_handler = logging.FileHandler(file_path, 'a', encoding='utf-8')
fmt = logging.Formatter(fmt="%(asctime)s - %(name)s - %(levelname)s: %(message)s")
file_handler.setFormatter(fmt)
self.logger = logging.Logger('cmdb', level=level)
self.logger.addHandler(file_handler)
def error(self, msg):
self.logger.error(msg)
logger = Logger("你的日志存放路径", logging.DEBUG)
logger.error(traceback.format_exc()) # 获取异常堆栈信息
class BaseResponse(object):
def __init__(self, status=True, data=None, error=None):
self.status = status
self.data = data
self.error = error
@property # 作用:让调用着不用加()
def dict(self):
return self.__dict__
def get_server_info(ssh, hostname):
server_info = {}
for key, path in settings.PLUGIN_CLASS_DICT.items():
module_path, class_name = path.rsplit('.', maxsplit=1)
try:
module = importlib.import_module(module_path)
except Exception as e:
print(e)
cls = getattr(module, class_name)
plugin_obj = cls()
info = plugin_obj.process(ssh, hostname)
server_info[key] = info
return server_info
# settings.py
# 获取计算机信息配置
PLUGIN_CLASS_DICT = {
'basic': 'lib.plugin.basic.BasicPlugin',
'disk': 'lib.plugin.disk.DiskPlugin',
'memory': 'lib.plugin.memory.MemoryPlugin',
'network': 'lib.plugin.network.NetworkPlugin',
}
# disk.py
import traceback
from lib.utils.log import logger
from lib.utils.response import BaseResponse
class DiskPlugin(BasePlugin):
"""
获取磁盘信息
"""
def process(self, ssh, hostname):
result = BaseResponse()
try:
# output = ssh(hostname, 'MegaCli -PDList -aALL')
output = open('files/disk.out').read()
result.data = output
output.close()
except Exception as e:
logger.error(traceback.format_exc())
result.status = False
result.error = traceback.format_exc()
return result.dict
cpu:
cat /proc/cpuinfo
主板:
dmidecode -t1
内存:
dmidecode -q -t 17 2>/dev/null
网卡(salt源码):
ip link show
ip addr show
硬盘:
MegaCli -PDList -aALL
手机扫一扫
移动阅读更方便
你可能感兴趣的文章