import os
import socket
def check_the_memory():
ip_list = {
‘47.9.3.15’: '10.8.6.3 ',
}
hostname = socket.gethostname() #获取计算机名称
ip_adress = socket.gethostbyname(hostname)
# print('ip_adress = ', ip_adress)
for k, v in ip_list.items():
if ip_adress == v:
ip_adress = k + ' -- ' + v
memory_list = os.popen('ps -aux | grep python3').readlines()
# print('memory_list = ', memory_list)
for m in memory_list:
# memory_data = {
# 'user': None, # 进程的属主
# 'pid': None, # 进程的ID
# 'cpu': None, # 进程占用的CPU百分比
# 'mem': None, # 占用内存的百分比
# 'VSZ': None, # 进程使用的虚拟內存量(KB)
# 'RSS': None, # 该进程占用的固定內存量(KB)(驻留中页的数量)
# 'TTY': None, # 该进程在那個終端上運行(登陸者的終端位置),若與終端無關,則顯示(?)。若为pts/0等,则表示由网络连接主机进程
# 'STAT': None, # 狀態位常見的狀態字符
# 'START': None, # 該進程被觸發启动时间
# 'TIME': None, # 該进程實際使用CPU運行的时间
# 'COMMAND': None, # 命令的名称和参数
# }
if '/app/bin/splash' in m: # 只选择 splash 服务
memory_data = [mm for mm in m.split(' ') if mm]
if float(memory_data[3]) > float(75):
# 杀死splash服务
os.popen('kill -9 %s' % int(memory_data[1]))
# 重新启动docker和splash
os.system("service docker restart")
os.system(r"(docker run -p 8050:8050 scrapinghub/splash &)")
shell_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(int(time.time())))
# 查询重启后占用内存及cpu
time.sleep(10)
memory_result = os.popen('ps -aux | grep python3').readlines()
for m_r in memory_result:
if '/app/bin/splash' in m_r: # 只选择 splash 服务
memory_data_result = [mm for mm in m_r.split(' ') if mm]
break
# shell_params = '1'
info = f'''
信息:{str(memory_data)}
kill: {memory_data[1]}
重启前占用内存:{float(memory_data[3])},
重启前占用cpu:{float(memory_data[2])},
重启时间:{shell_time}
重启结果:'已重启',
重启后占用内存:{float(memory_data_result[3])},
重启后占用cpu:{float(memory_data_result[2])},
机器地址:{ip_adress}
'''
send_email(info)
break