This commit is contained in:
emre.akkaya 2016-06-09 15:30:53 +03:00
commit d596b9bd79
5 changed files with 198 additions and 70 deletions

3
debian/control vendored
View file

@ -9,5 +9,4 @@ Homepage: http://www.liderahenk.org.tr
Package: ahenk Package: ahenk
Architecture: any Architecture: any
Depends:python3 (>= 3), cython, libidn11, libidn11-dev, slixmpp, python3-dev, python3-pip, libffi-dev, libssl-dev, python3-paramiko, python3-psutil Depends:python3 (>= 3), cython, libidn11, libidn11-dev, slixmpp, python3-dev, python3-pip, libffi-dev, libssl-dev, python3-paramiko, python3-psutil
Description: LiderAhenk agent application Description: Lider Ahenk is an open source project which provides solutions to manage, monitor and audit unlimited number of different systems and users on a network.
Long Desc

View file

@ -180,7 +180,7 @@ class Commander(object):
def status(self): def status(self):
ahenk_state = False ahenk_state = False
if System.Ahenk.get_pid_number(): if System.Ahenk.is_running() is True:
ahenk_state = True ahenk_state = True
return "Ahenk Active:{0}\nInstalled Plugins:{1}".format(ahenk_state, str(System.Ahenk.installed_plugins())) return "Ahenk Active:{0}\nInstalled Plugins:{1}".format(ahenk_state, str(System.Ahenk.installed_plugins()))

View file

@ -105,8 +105,8 @@ class Registration():
'os.distributionVersion': System.Os.distribution_version(), 'os.distributionVersion': System.Os.distribution_version(),
'os.architecture': System.Os.architecture(), 'os.architecture': System.Os.architecture(),
'hardware.cpu.architecture': System.Hardware.Cpu.architecture(), 'hardware.cpu.architecture': System.Hardware.Cpu.architecture(),
'hardware.cpu.logicalCoreCount': System.Hardware.Cpu.logical_core_count(), # 'hardware.cpu.logicalCoreCount': System.Hardware.Cpu.logical_core_count(),
'hardware.cpu.physicalCoreCount': System.Hardware.Cpu.physical_core_count(), # 'hardware.cpu.physicalCoreCount': System.Hardware.Cpu.physical_core_count(),
'hardware.disk.total': System.Hardware.Disk.total(), 'hardware.disk.total': System.Hardware.Disk.total(),
'hardware.disk.used': System.Hardware.Disk.used(), 'hardware.disk.used': System.Hardware.Disk.used(),
'hardware.disk.free': System.Hardware.Disk.free(), 'hardware.disk.free': System.Hardware.Disk.free(),

View file

@ -4,11 +4,17 @@
import platform import platform
import psutil import psutil
import cpuinfo # import cpuinfo
import re import re
import os import os
import configparser import configparser
import socket
import fcntl
import struct
from uuid import getnode as get_mac
"""
some functions closed because of dependency management
"""
class System: class System:
class Ahenk(object): class Ahenk(object):
@ -58,18 +64,14 @@ class System:
@staticmethod @staticmethod
def is_running(): def is_running():
try: try:
if System.Ahenk.get_pid_number() is not None: if System.Ahenk.get_pid_number() is not None:
if psutil.Process(int(System.Ahenk.get_pid_number())).is_running() is True: return psutil.pid_exists(int(System.Ahenk.get_pid_number()))
return True
else: else:
return False return False
except Exception as e: except Exception as e:
return False return False
@staticmethod @staticmethod
def config_path(): def config_path():
return '/etc/ahenk/ahenk.conf' return '/etc/ahenk/ahenk.conf'
@ -80,26 +82,48 @@ class System:
class Process(object): class Process(object):
@staticmethod
def process_by_pid(pid):
return psutil.Process(pid)
"""
@staticmethod @staticmethod
def pids(): def pids():
return psutil.pids() return psutil.pids()
@staticmethod @staticmethod
def find_pid_by_name(p_name): def find_pid_by_name(p_name):
for id in psutil.pids(): for id in psutil.pids():
if psutil.Process(id).name() == p_name: if psutil.Process(id).name() == p_name:
return id return id
return None return None
"""
@staticmethod
def find_pids_by_name(p_name):
arr = []
for pid in psutil.get_pid_list():
if psutil.Process(pid).name==p_name:
arr.append(pid)
return arr
@staticmethod @staticmethod
def process_by_pid(pid): def is_running(pid):
return psutil.Process(pid) return psutil.pid_exists(pid)
@staticmethod @staticmethod
def kill_by_pid(pid): def kill_by_pid(pid):
return psutil.Process(pid).kill() return psutil.Process(pid).kill()
@staticmethod
def kill_by_pids(pids):
for pid in pids:
psutil.Process(pid).kill()
@staticmethod @staticmethod
def find_name_by_pid(pid): def find_name_by_pid(pid):
return psutil.Process(pid).name() return psutil.Process(pid).name()
@ -108,9 +132,11 @@ class System:
def path(pid): def path(pid):
return psutil.Process(pid).exe() return psutil.Process(pid).exe()
"""
@staticmethod @staticmethod
def working_directory(pid): def working_directory(pid):
return psutil.Process(pid).cwd() return psutil.Process(pid).cwd()
"""
@staticmethod @staticmethod
def command_line(pid): def command_line(pid):
@ -128,6 +154,9 @@ class System:
def create_time(pid): def create_time(pid):
return psutil.Process(pid).create_time() return psutil.Process(pid).create_time()
"""
@staticmethod @staticmethod
def cpu_times(pid): def cpu_times(pid):
return psutil.Process(pid).cpu_times() return psutil.Process(pid).cpu_times()
@ -151,14 +180,17 @@ class System:
@staticmethod @staticmethod
def threads(pid): def threads(pid):
return psutil.Process(pid).threads() return psutil.Process(pid).threads()
"""
@staticmethod @staticmethod
def nice(pid): def nice(pid):
return psutil.Process(pid).nice() return psutil.Process(pid).nice()
"""
@staticmethod @staticmethod
def environment(pid): def environment(pid):
return psutil.Process(pid).environ() return psutil.Process(pid).environ()
"""
@staticmethod @staticmethod
def details(): def details():
@ -166,6 +198,15 @@ class System:
class Sessions(object): class Sessions(object):
@staticmethod
def user_name():
arr = []
for user in psutil.get_users():
if str(user[0]) is not 'None' and user[0] not in arr:
arr.append(user[0])
return arr
"""
@staticmethod @staticmethod
def user_name(): def user_name():
arr = [] arr = []
@ -178,6 +219,10 @@ class System:
def user_details(): def user_details():
return psutil.users() return psutil.users()
"""
@staticmethod @staticmethod
def last_login_username(): def last_login_username():
# TODO # TODO
@ -185,14 +230,17 @@ class System:
class Os(object): class Os(object):
@staticmethod
def boot_time():
return psutil.boot_time()
@staticmethod @staticmethod
def architecture(): def architecture():
return platform.architecture()[0] return platform.architecture()[0]
"""
@staticmethod
def boot_time():
return psutil.boot_time()
"""
@staticmethod @staticmethod
def file_format(): def file_format():
return platform.architecture()[1] return platform.architecture()[1]
@ -277,10 +325,6 @@ class System:
def interface_size(): def interface_size():
return len(psutil.net_io_counters(pernic=True)) return len(psutil.net_io_counters(pernic=True))
@staticmethod
def interfaces_details():
return psutil.net_if_addrs()
@staticmethod @staticmethod
def io_counter_detail(): def io_counter_detail():
return psutil.net_io_counters(pernic=True) return psutil.net_io_counters(pernic=True)
@ -288,7 +332,7 @@ class System:
@staticmethod @staticmethod
def interfaces(): def interfaces():
arr = [] arr = []
for iface in psutil.net_if_addrs(): for iface in psutil.net_io_counters(pernic=True):
arr.append(str(iface)) arr.append(str(iface))
return arr return arr
@ -296,38 +340,71 @@ class System:
def ip_addresses(): def ip_addresses():
arr = [] arr = []
for iface in psutil.net_io_counters(pernic=True): for iface in psutil.net_io_counters(pernic=True):
ip = psutil.net_if_addrs()[str(iface)][0][1] f = os.popen('ifconfig {} | grep "inet\ addr" | cut -d: -f2 | cut -d" " -f1'.format(iface))
if re.match(r'^((\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$', ip) and str(ip) != 'localhost' and str(ip) != '127.0.0.1': ip = str(f.read()).replace('\n', '')
if ip != '127.0.0.1':
arr.append(ip) arr.append(ip)
return arr return arr
"""
@staticmethod
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
@staticmethod
def getHwAddr(ifname):
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
info = fcntl.ioctl(s.fileno(), 0x8927, struct.pack('256s', ifname[:15]))
return ''.join(['%02x:' % ord(char) for char in info[18:24]])[:-1]
@staticmethod
def mac_addresses():
mac = get_mac()
':'.join(("%012X" % mac)[i:i+2] for i in range(0, 12, 2)
arr = []
for iface in psutil.net_io_counters(pernic=True):
try:
addr_list = psutil.net_if_addrs()
mac = addr_list[str(iface)][2][1]
if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()) and str(mac) != '00:00:00:00:00:00':
arr.append(mac.lower())
except Exception as e:
pass
# return arr
"""
@staticmethod @staticmethod
def mac_addresses(): def mac_addresses():
arr = [] arr=[]
for iface in psutil.net_io_counters(pernic=True): for iface in psutil.net_io_counters(pernic=True):
try: mac = open('/sys/class/net/' + iface + '/address').readline()
addr_list=psutil.net_if_addrs() if str(mac[0:17]) != "00:00:00:00:00:00":
mac = addr_list[str(iface)][2][1] arr.append(mac[0:17])
if re.match("[0-9a-f]{2}([-:])[0-9a-f]{2}(\\1[0-9a-f]{2}){4}$", mac.lower()) and str(mac) != '00:00:00:00:00:00':
arr.append(mac.lower())
except Exception as e:
pass
return arr return arr
"""
@staticmethod
def interfaces_details():
return psutil.net_if_addrs()
@staticmethod
def ip_addresses():
arr = []
for iface in psutil.net_io_counters(pernic=True):
ip = psutil.net_if_addrs()[str(iface)][0][1]
if re.match(r'^((\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])\.){3}(\d{1,2}|1\d{2}|2[0-4]\d|25[0-5])$', ip) and str(ip) != 'localhost' and str(ip) != '127.0.0.1':
arr.append(ip)
return arr
"""
class Cpu(object): class Cpu(object):
@staticmethod
def physical_core_count():
return psutil.cpu_count(logical=False)
@staticmethod
def logical_core_count():
return psutil.cpu_count(logical=True)
@staticmethod
def stats():
return psutil.cpu_stats()
@staticmethod @staticmethod
def times(): def times():
return psutil.cpu_times() return psutil.cpu_times()
@ -336,31 +413,47 @@ class System:
def architecture(): def architecture():
return platform.processor() return platform.processor()
@staticmethod """
def vendor(): @staticmethod
return cpuinfo.get_cpu_info()['vendor_id'] def physical_core_count():
return psutil.cpu_count(logical=False)
@staticmethod @staticmethod
def brand(): def logical_core_count():
return cpuinfo.get_cpu_info()['brand'] return psutil.cpu_count(logical=True)
@staticmethod @staticmethod
def hz_advertised(): def stats():
return cpuinfo.get_cpu_info()['hz_advertised'] return psutil.cpu_stats()
"""
@staticmethod """
def hz_actual(): @staticmethod
return cpuinfo.get_cpu_info()['hz_actual'] def vendor():
return cpuinfo.get_cpu_info()['vendor_id']
@staticmethod @staticmethod
def bit(): def brand():
return cpuinfo.get_cpu_info()['bits'] return cpuinfo.get_cpu_info()['brand']
@staticmethod @staticmethod
def family(): def hz_advertised():
return cpuinfo.get_cpu_info()['family'] return cpuinfo.get_cpu_info()['hz_advertised']
@staticmethod @staticmethod
def model(): def hz_actual():
return cpuinfo.get_cpu_info()['model'] return cpuinfo.get_cpu_info()['hz_actual']
@staticmethod
def bit():
return cpuinfo.get_cpu_info()['bits']
@staticmethod
def family():
return cpuinfo.get_cpu_info()['family']
@staticmethod
def model():
return cpuinfo.get_cpu_info()['model']
"""

View file

@ -9,6 +9,7 @@ import pwd
import shutil import shutil
import stat import stat
import subprocess import subprocess
import sys
class Util: class Util:
@ -115,16 +116,19 @@ class Util:
raise raise
@staticmethod @staticmethod
def execute(command, stdin=None, env=None, cwd=None, shell=True): def execute(command, stdin=None, env=None, cwd=None, shell=True, result=True):
try: try:
process = subprocess.Popen(command, stdin=stdin, env=env, cwd=cwd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=shell) process = subprocess.Popen(command, stdin=stdin, env=env, cwd=cwd, stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=shell)
result_code = process.wait() if result is True:
p_out = process.stdout.read().decode("unicode_escape") result_code = process.wait()
p_err = process.stderr.read().decode("unicode_escape") p_out = process.stdout.read().decode("unicode_escape")
p_err = process.stderr.read().decode("unicode_escape")
return result_code, p_out, p_err return result_code, p_out, p_err
else:
return None, None, None
except Exception as e: except Exception as e:
return 1, 'Could not execute command: {0}. Error Message: {1}'.format(command, str(e)), '' return 1, 'Could not execute command: {0}. Error Message: {1}'.format(command, str(e)), ''
@ -183,3 +187,35 @@ class Util:
return grp.getgrgid(gid)[0] return grp.getgrgid(gid)[0]
except: except:
raise raise
@staticmethod
def install_with_gdebi(full_path):
try:
process = subprocess.Popen('gdebi -n ' + full_path, shell=True)
process.wait()
except:
raise
@staticmethod
def install_with_apt_get(package_name):
try:
process = subprocess.Popen('apt-get install --yes --force-yes ' + package_name, shell=True)
process.wait()
except:
raise
@staticmethod
def is_installed(package_name):
result_code, p_out, p_err = Util.execute('dpkg -s {}'.format(package_name))
try:
lines=str(p_out).split('\n')
for line in lines:
if len(line)>1:
if line.split(None, 1)[0].lower() =='status:':
if 'installed' in line.split(None, 1)[1].lower():
return True
return False
except Exception as e:
return False