基础版,仅检测服务状态
使用paramiko登录目标服务器检查某个服务的状态
import paramiko
#创建SSH对象
ssh = paramiko.SSHClient()
#把要连接的机器添加到known_hosts文件中
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
#连接服务器
ssh.connect(hostname='10.178.101.21', port=22, username='mia', password='1234')
cmd = 'service unattended-upgrades status'
#cmd = 'ls -l;ifconfig' #多个命令用;隔开
stdin, stdout, stderr = ssh.exec_command(cmd)
result = stdout.read()
if not result:
result = stderr.read()
ssh.close()
result_decode = result.decode()
if 'active (running)' in result_decode:
print('服务在运行')
else:
print('服务挂了')
#print(result_decode)
高级版,检测更多信息
检查服务状态和主机存活情况,如果服务关掉之后自动开启
import paramiko
import os
import sys
import json
import time
import datetime
import socket
import subprocess
# Ping存活检测
def ping_check(ip):
cmd_res = subprocess.Popen('ping -n 2 '+ip,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding='gbk')
result = cmd_res.stdout.read()
if 'TTL' in result or "ttl" in result:
return True
else:
return False
# ping_check("192.168.31.1")
# 端口开放检测
def port_check(ip, port):
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
result = sock.connect_ex((ip, int(port)))
if result == 0:
return True
else:
return False
# port_check("192.168.31.1", 443)
# 吸收会话回显
def session_callback(session,username,end_mark):
cache = ""
while True:
cache = session.recv(4096).decode('utf-8')
if username in cache and cache.endswith(end_mark):
break;
return cache
def ssh_get(ip, port, username, password, service, if_start_service):
# 执行最后默认返回字符
end_mark = "# "
# 实例化SSHClient
sclient = paramiko.SSHClient()
# 自动添加策略,保存服务器的主机名和密钥信息
sclient.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# 连接SSH服务端,以用户名和密码进行认证
sclient.connect(hostname=ip, username=username, password=password, look_for_keys=False)
session = sclient.invoke_shell()
# 设置会话回显超时时间
session.settimeout(3600)
# 获取登陆后的消息
welcomeinfo = session_callback(session,username,end_mark)
# 此处选择是否打印BANNER
# print(welcomeinfo)
# 获取主机名部分
hostname_cmd = "cat /etc/hostname"
session.send(hostname_cmd+'\n')
hostname_cache = (session_callback(session,username,end_mark).replace("\r","\n")).split("\n")
hostname = hostname_cache[-3]
# 首先提权
session.send('sudo su\n')
session_callback(session,username,end_mark)
# 查看服务状态
session.send("systemctl status "+service+'\n')
caches = (session_callback(session,username,end_mark).replace("\r","\n")).split("\n")
service_status = ""
for line in caches:
if "Active:" in line and "active (running)" in line:
service_status = service+" is running"
elif "Active:" in line and "inactive" in line:
service_status = service+" is dead"
if if_start_service:
if service_status == service+" is dead":
session.send("systemctl start "+service+'\n')
session_callback(session,username,end_mark)
session.send("systemctl status "+service+'\n')
caches = (session_callback(session,username,end_mark).replace("\r","\n")).split("\n")
start_result = ""
for line in caches:
if "Active:" in line and "active (running)" in line:
start_result = ", now is running"
elif "Active:" in line and "inactive" in line:
start_result = ", now still dead"
service_status = service_status+start_result
result = [service_status,hostname]
return result
def mainfunction():
file = open("config.json", "rb")
json_config = json.load(file)
if json_config["if_start_service"] == "true":
if_start_service = True
else:
if_start_service = False
servers = json_config["servers"]
for i in servers:
if json_config["if_common_config"] == "true":
if json_config["common_ping_check"].upper() == "TRUE":
if ping_check(i["host"]):
print("host ping alive")
if json_config["common_port_check"].upper() != "FALSE":
if port_check(i["host"],json_config["common_port_check"]):
print("port "+json_config["common_port_check"]+" open")
ssh_result = ssh_get(i["host"],json_config["common_port"],json_config["common_username"],json_config["common_password"],json_config["common_service"],if_start_service)
print("hostname: "+ssh_result[1])
print("service status: "+ssh_result[0])
else:
if i["ping_check"].upper() == "TRUE":
if ping_check(i["host"]):
print("host ping alive")
if i["port_check"].upper() != "FALSE":
if port_check(i["host"],i["port_check"]):
print("port "+i["port_check"]+" open")
ssh_result = ssh_get(i["host"],i["port"],i["username"],i["password"],i["service"],if_start_service)
print("hostname: "+ssh_result[1])
print("service status: "+ssh_result[0])
sys.exit(0)
mainfunction()
配置文件
{
"servers":
[{
"host": "47.112.171.126",
"service": "rsyslog.service",
"port": "22",
"username": "root",
"password": "G1",
"ping_check":"true",
"port_check":"22"
}],
"if_start_service":"true",
"if_common_config":"false",
"common_username":"root",
"common_password":"G1",
"common_port":"22",
"common_service":"rsyslog.service",
"common_ping_check":"true",
"common_port_check":"22"
}