Advertisement
Guest User

Untitled

a guest
Dec 21st, 2014
211
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.10 KB | None | 0 0
  1. #! /usr/bin/python3
  2. import sys
  3. import os
  4. import re
  5. import json
  6. import crypt
  7. import hashlib
  8. import datetime
  9.  
  10. # Arguments
  11. action      =   str(sys.argv[1])
  12. serverid    =   int(sys.argv[2])
  13. game        =   str(sys.argv[3])
  14. ip          =   str(sys.argv[4])
  15. port        =   int(sys.argv[5])
  16. slots       =   int(sys.argv[6])
  17. password    =   str(sys.argv[7])
  18.  
  19. salt = 'tlas'
  20. username = 'gs' + str(serverid)
  21.  
  22. gameConfig = None
  23.  
  24. def md5file(filePath):
  25.     f = open(filePath, 'rb')
  26.     md5 = hashlib.md5()
  27.     while True:
  28.         data = f.read(8192)
  29.         if not data:
  30.             break
  31.         md5.update(data)
  32.     f.close()
  33.     return md5.hexdigest()
  34.  
  35. def loadGameConfig():
  36.     global gameConfig
  37.     f = open('/home/cp/gameservers/configs/' + game + '.cfg', 'r')
  38.     data = f.read()
  39.     gameConfig = json.loads(data)
  40.     f.close()
  41.  
  42. def serverStatus():
  43.     p = os.popen('su -lc "screen -ls | grep -c gameserver" ' + username)
  44.     count = int(p.readline())
  45.     p.close()
  46.     if count > 0:
  47.         return True
  48.     else:
  49.         return False
  50.  
  51. def serverCheckFiles():
  52.     for file in gameConfig['Files']:
  53.         if not os.path.isfile('/home/' + username + file['File']):
  54.             if file['Required'] == 1:
  55.                 return False
  56.             else:
  57.                 continue
  58.        
  59.         fileHash = md5file('/home/' + username + file['File'])
  60.         if not fileHash in file['Hashes']:
  61.             return False
  62.     return True
  63.  
  64. def serverConfigure():
  65.     configs = gameConfig['Configs']
  66.     for config in configs:
  67.         # Check config file
  68.         if not os.path.isfile('/home/' + username + config['File']):
  69.             if config['Required'] == 1:
  70.                 return False
  71.             else:
  72.                 continue
  73.        
  74.         # Read config
  75.         f = open('/home/' + username + config['File'], 'r')
  76.         data = f.read()
  77.         f.close()
  78.        
  79.         # Append exec configs
  80.         if(config['ExecPattern']):
  81.             execPattern = config['ExecPattern'].replace("<value>", "(.*)");
  82.             execConfigs = re.findall(execPattern, data)
  83.             for execConfig in execConfigs:
  84.                 configPath = os.path.dirname(config['File']) + '/' + execConfig
  85.                 configs.append({
  86.                     "File": configPath,
  87.                     "Required": 0,
  88.                     "ExecPattern": config['ExecPattern'],
  89.                     "Values": [dict(i, Required = 0) for i in config['Values']]
  90.                 })
  91.        
  92.         # Check configs values
  93.         for value in config['Values']:
  94.             pattern = value['Pattern'].replace('<value>', '(.*)')
  95.            
  96.             if value['Value'] == '__ip__':
  97.                 replace = value['Pattern'].replace('<value>', ip)
  98.             elif value['Value'] == '__port__':
  99.                 replace = value['Pattern'].replace('<value>', str(port))
  100.             elif value['Value'] == '__port2__':
  101.                 replace = value['Pattern'].replace('<value>', str(port + 1))
  102.             elif value['Value'] == '__port3__':
  103.                 replace = value['Pattern'].replace('<value>', str(port + 1000))
  104.             elif value['Value'] == '__slots__':
  105.                 replace = value['Pattern'].replace('<value>', str(slots))
  106.             else:
  107.                 replace = value['Pattern'].replace('<value>', value['Value'])
  108.            
  109.             data = re.sub(pattern, replace, data)
  110.            
  111.             # Required, but not found
  112.             if value['Required'] == 1 and not re.search(pattern, data):
  113.                 return False
  114.             # Not required, but found
  115.             elif value['Required'] == -1 and re.search(pattern, data):
  116.                 return False
  117.        
  118.         # Rewrite config
  119.         f = open('/home/' + username + config['File'], 'w')
  120.         f.write(data)
  121.         f.close()
  122.     return True
  123.  
  124. def serverInstall():
  125.     os.system('useradd -m -g gameservers -p ' + crypt.crypt(password, salt) + ' ' + username)
  126.     for archive in gameConfig['Archives']:
  127.         os.system('tar -xf /home/cp/gameservers/files/' + archive + '.tar -C /home/' + username + '/')
  128.     os.system('chown ' + username + ' -Rf /home/' + username)
  129.     os.system('chmod 700 /home/' + username)
  130.     return True
  131.  
  132. def serverReinstall():
  133.     os.system('rm -Rf /home/' + username + '/*')
  134.     for archive in gameConfig['Archives']:
  135.         os.system('tar -xf /home/cp/gameservers/files/' + archive + '.tar -C /home/' + username + '/')
  136.     os.system('chown ' + username + ' -Rf /home/' + username)
  137.     return True
  138.  
  139. def serverStart():
  140.     execCmd = gameConfig['ExecCmd']
  141.     execCmd = execCmd.replace('@ip@', ip)
  142.     execCmd = execCmd.replace('@port@', str(port))
  143.     execCmd = execCmd.replace('@port2@', str(port+1))
  144.     execCmd = execCmd.replace('@port3@', str(port+1000))
  145.     execCmd = execCmd.replace('@slots@', str(slots))
  146.     os.system('su -lc "screen -AmdS gameserver ' + execCmd + '" ' + username)
  147.     return True
  148.  
  149. def serverStop():
  150.     os.system('su -lc "screen -r gameserver -X quit " ' + username)
  151.     return True
  152.  
  153. def serverUpdatePassword():
  154.     os.system('usermod -p ' + crypt.crypt(password, salt) + ' ' + username)
  155.     return True
  156.  
  157. def serverDelete():
  158.     os.system('userdel -rf ' + username)
  159.     return True
  160.  
  161. def serverSysLoad():
  162.     cpu = 0.0
  163.     ram = 0.0
  164.    
  165.     p = os.popen("ps u -U gs" + str(serverid) + " | awk '{print $3\"\t\"$4}'")
  166.     line = p.readline()
  167.    
  168.     while line:
  169.         result = re.match("([0-9]+\.[0-9]+)\t([0-9]+\.[0-9]+)", line)
  170.         if(result):
  171.             cpu += float(result.group(1))
  172.             ram += float(result.group(2))
  173.         line = p.readline()
  174.    
  175.     p.close()
  176.     print('[[' + str(cpu) + '::' + str(ram) + ']]')
  177.  
  178. def returnResult(status, description):
  179.     date = datetime.datetime.today()
  180.     filename = date.strftime('%d-%m-%y') + '.xls'
  181.     if os.path.isfile('/home/cp/logs/' + filename):
  182.         # Open file
  183.         f = open('/home/cp/logs/' + filename, 'a')
  184.     else:
  185.         # Create file
  186.         f = open('/home/cp/logs/' + filename, 'w')
  187.         f.write('TIME,SERVERID,STATUS,DESCRIPTION\n')
  188.    
  189.     f.write(date.strftime('%H:%M:%S') + ',' + str(serverid) + ',' + status + ',' + description + '\n')
  190.     f.close()
  191.    
  192.     # Print result and exit
  193.     print('[[' + status + '::' + description + ']]')
  194.     exit(0)
  195.  
  196. loadGameConfig()
  197.  
  198. if action == 'install':
  199.     if not serverInstall():
  200.         returnResult('ERROR', 'InstallError')
  201.     elif not serverConfigure():
  202.         returnResult('ERROR', 'ConfigError')
  203.     else:
  204.         returnResult('OK', '')
  205.  
  206. if action == 'reinstall':
  207.     if serverStatus():
  208.         if not serverStop():
  209.             returnResult('ERROR', 'StopError')
  210.    
  211.     if not serverReinstall():
  212.         returnResult('ERROR', 'ReinstallError')
  213.     elif not serverConfigure():
  214.         returnResult('ERROR', 'ConfigError')
  215.     else:
  216.         returnResult('OK', '')
  217.  
  218. if action == 'start':
  219.     if serverStatus():
  220.         if not serverStop():
  221.             returnResult('ERROR', 'StopError')
  222.    
  223.     if not serverCheckFiles():
  224.         returnResult('ERROR', 'FilesError')
  225.     elif not serverConfigure():
  226.         returnResult('ERROR', 'ConfigError')
  227.     elif not serverStart():
  228.         returnResult('ERROR', 'StartError')
  229.     else:
  230.         returnResult('OK', '')
  231.  
  232. if action == 'stop':
  233.     if not serverStop():
  234.         returnResult('ERROR', 'StopError')
  235.     else:
  236.         returnResult('OK', '')
  237.  
  238. if action == 'restart':
  239.     if not serverStop():
  240.         returnResult('ERROR', 'StopError')
  241.     elif not serverCheckFiles():
  242.         returnResult('ERROR', 'FilesError')
  243.     elif not serverConfigure():
  244.         returnResult('ERROR', 'ConfigError')
  245.     elif not serverStart():
  246.         returnResult('ERROR', 'StartError')
  247.     else:
  248.         returnResult('OK', '')
  249.  
  250. if action == 'delete':
  251.     if serverStatus():
  252.         serverStop()
  253.    
  254.     if not serverDelete():
  255.         returnResult('ERROR', 'DeleteError')
  256.     else:
  257.         returnResult('OK', '')
  258.  
  259. if action == 'updatepassword':
  260.     if serverStatus():
  261.         if not serverStop():
  262.             returnResult('ERROR', 'StopError')
  263.    
  264.     if not serverUpdatePassword():
  265.         returnResult('ERROR', 'UpdatePasswordError')
  266.     else:
  267.         returnResult('OK', '')
  268.  
  269.  
  270. if action == 'sysload':
  271.     serverSysLoad()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement