Jump to content

Cube World Server Utility


Dateranoth
 Share

Recommended Posts

Updated July 20, 2013!

Utility for logging Cube World Server, restarting daily, restarting on crashes, closing crash window, and remotely restarting.

Download Utility Here (Logging Batch File and AutoIT Script)

Download Stand Alone AutoIT Script Here (No Batch File Required)

Download Remote Restart Utility Here (Requires one of the AutoIT Scripts to be running. Allows Server to be remotely Restarted)Batch File and AutoIT Script designed to work together. The AutoIT Script is not required, but they work better together.  There is a stand alone AutoIT Script below that doesn't require the Batch file.  Finally, I have included a AutoIT Script to remotely restart the server when used with one of the Server Scripts.

The remote restart will require you edit the source of the AutoIT scripts if you wish to change the listening IP, port, and password required for restart. They should work together by default, but you will need to open port 54321 on the Server.

::V1.1-Added Task Kill of AutoIT Script to be used along side batch----------::::V1.0-Initial Version Created. Simple Loop Script for Server Crashes--------::::-----Also added ability to log server to file------------------------------::
Batch File:
@ECHO OFFtitle Cube Server Loop Utility::By Dateranoth - July 7, 2013::Used by http://www.gamercide.org on their server.::Feel free to change, adapt, and distribute::Download batch file here-::http://www.dateranoth.com/gamercide/CWServerUtility.zip::V1.1-Added Task Kill of AutoIT Script to be used along side batch----------::::V1.0-Initial Version Created. Simple Loop Script for Server Crashes--------::::-----Also added ability to log server to file------------------------------::::-----------------------------------------------------------------------------------::::--------------------User Variables--------------------------------- ----------------::::-----------------------------------------------------------------------------------::::Set Server.exe Directory (Be sure to include Trailing Slash)SET ServerPath=C:\Games\Cube World\::Set Time between server Failed or Stopped and Server Restarted (in seconds)SET Timer=10::-----------------------------------------------------------------------------------::::----------------Logging Options - Enable Logging Here------------------------------::::-----------------------------------------------------------------------------------::::If Logging is enabled, the Console will not output current server status. ::All status will be written to file. You can check current status through the log file.::Log Server to file containing todays date. (yes or no)set EnableLog=no::LogPath is the path to the folder where the log file will be saved (Be sure to include Trailing Slash)set LogPath=C:\Games\Cube World\Logs\::LogFileExt is the extension to be used set LogFileExt=.log::LogFile is a descriptive name that will be added after the dateset LogFile=CubeWorldServerLog::Include Time In Log File Name? (yes or no)::Including time will create a log file on each Server.exe start.  Not including time will create Daily Log files.set IncludeTime=no::Set the format you would like the date to appear on log files. Default is year(%%g)-month(%%e)-day(%%f). Your windows time format may differ.:: If it does or you would like something different then rearrange the parameters below until satisfied. Results will be format1-format2-format3set dateformat1=%%gset dateformat2=%%eset dateformat3=%%f::------------------------------------------------------------------------------------------------------------------------------::::!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!No Setting Changes Below Here!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!::::------------------------------------------------------------------------------------------------------------------------------:::Start::start /wait /min /d "%ServerPath%" Server.exeIF /i %EnableLog%==yes (goto LoggingStart) ELSE (goto NoLogStart):NoLogStartECHO.ECHO Starting Server Loop.ECHO.cd /d "%ServerPath%""%ServerPath%"Server.exegoto RemainingLoop:LoggingStartsetlocalset LogFileName=%LogFile%%LogFileExt%for /f "tokens=1-5 delims=/\ " %%d in ("%date%") do SET Date1=%dateformat1%-%dateformat2%-%dateformat3%for /f "tokens=1-5 delims=: " %%d in ("%time%") do SET Time1=%%d%%eIF /i %IncludeTime%==yes (set MyLogFile=%Date1%--%Time1%) ELSE (set MyLogFile=%Date1%)set MyLogFile=%LogPath%%MyLogFile%_%LogFileName%If NOT Exist "%LogPath%" (goto makelogdirectory) ELSE (goto checknewlog):makelogdirectorymd "%LogPath%"goto checknewlog::Note that the quotes are REQUIRED around %MyLogFIle% in case it contains a space:checknewlogIf NOT Exist "%MyLogFile%" (goto noseparator)Echo.>>"%MyLogFile%"Echo.===================>>"%MyLogFile%":noseparatorecho.%Date% >>"%MyLogFile%"echo.%Time% >>"%MyLogFile%":startbatchECHO.ECHO Starting Server Loop and Logging.ECHO.ECHO.ECHO Server will not display to Console while logging to file is enabled.ECHO.ECHO To check server status, open:ECHO %MyLogFile%ECHO.ECHO Type q to quit.ECHO.cd /d "%ServerPath%""%ServerPath%"Server.exe >> "%MyLogFile%"goto RemainingLoop::Checks if timer has counted down to 0. If so restarts backup:RemainingLoopsetlocal enableDelayedExpansionfor /l %%N in (%Timer% -1 1) do (  set /a "min=%%N/60, sec=%%N%%60, n-=1"  if !sec! lss 10 set sec=0!sec!  cls  choice /c:CR1 /n /m "Server Restart in !min!:!sec! - Press R to Restart Server Now, or C to Cancel. " /t:1 /d:1  if not errorlevel 3 goto :CheckAnswer):CheckAnswerif errorlevel 2 (goto Start) else (goto End)::Shut Down The Batch File.:Endchoice /c:YN /m "Do you really want to quit"If Errorlevel 2 goto StartIf Errorlevel 1 goto Shutdown:Shutdowntaskkill /f /im "CWServerUtility.exe"Exit::Here in case of any major errors.:CatchAllEndpauseExit
Autoit Script (Use with Batch):

#include <Date.au3>#include <Process.au3>;User VariablesLocal $g_IP = "127.0.0.1" ;IP Restart Command Should Listen OnLocal $g_Port = "54321" ;Port Restart Command Should Listen OnLocal $RestartCode = "Restart" ;Code to Reset Server;End User VariablesLocal $HotMin = "01"If Not IsDeclared("sInputBoxAnswer") Then Local $sInputBoxAnswer$sInputBoxAnswer = InputBox("Cube World Auto Restart and Daily Restart","What hour of the day do you want to Restart?" & @CRLF & @CRLF & "Note:  Please use a number value between 00 and 23" & @CRLF & "           00 means midnight, 14 would be 2pm, etc." & @CRLF,"10", " M2","400","180","350","350","60")SelectCase @Error = 0 ;OK - The string returned is valid   Local $HotHour = $sInputBoxAnswerCase @Error = 1 ;The Cancel button was pushed   Exit     ; finishedCase @Error = 2 ;Timeout Reached   Local $HotHour = "10"Case @Error = 3 ;The InputBox failed to open   Exit     ; finishedEndSelectFunc _TCP_Server_ClientIP($hSocket)   Local $pSocketAddress, $aReturn   $pSocketAddress = DllStructCreate("short;ushort;uint;char[8]")   $aReturn = DllCall("ws2_32.dll", "int", "getpeername", "int", $hSocket, "ptr", DllStructGetPtr($pSocketAddress), "int*", DllStructGetSize($pSocketAddress))   If @error Or $aReturn[0] <> 0 Then Return $hSocket	  $aReturn = DllCall("ws2_32.dll", "str", "inet_ntoa", "int", DllStructGetData($pSocketAddress, 3))   If @error Then Return $hSocket	  $pSocketAddress = 0   Return $aReturn[0] EndFunc ;==>_TCP_Server_ClientIP; Start The TCP ServicesTCPStartup()Local $MainSocket = TCPListen($g_IP, $g_Port, 100)If $MainSocket = -1 Then Exitwhile True	if WinExists("Server.exe") Then		ControlSend("Server.exe", "", "", "{enter}")		Sleep (10000)	EndIfIf Not WinExists("Cube Server Loop Utility") Then   ;Run(@ScriptDir & "\Server.exe")   Run(@ComSpec & " /c " & 'CWServerUtility.bat', @ScriptDir)   Sleep (10000)EndIFLocal $ConnectedSocket = TCPAccept($MainSocket)If $ConnectedSocket >= 0 Then;TrayTip("Connected","Someone connected to server.",3)$Count = 0While $Count < 30$RECV = TCPRecv($ConnectedSocket,512)   If $RECV = $RestartCode Then   Local $PID = ProcessExists("Server.exe") ; Will return the PID or 0 if the process isn't found.   	  If $PID Then		 $IP = _TCP_Server_ClientIP($ConnectedSocket)		 Local $MEM = ProcessGetStats($PID, 0)		 FileWriteLine(@ScriptDir & "\RestartLog.txt", @MON &"-"& @MDAY &"-"& @YEAR &" "& @HOUR &":"& @MIN &" --Work Memory:"& $MEM[0] & _		 " --Peak Memory:"& $MEM[1] &" Restart Requested by Remote Host: "& $IP)		 ProcessClose($PID)		 Sleep (10000)		 ExitLoop	  EndIf   EndIf$Count += 1Sleep (1000)WEndIf $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket)EndIf	 Local $PID = ProcessExists("Server.exe")  If $PID Then   Local $MEM = ProcessGetStats($PID, 0)   If $MEM[0] > 600000000 Then	  FileWriteLine(@ScriptDir & "\ExcessiveMemoryLog.txt", @MON &"-"& @MDAY &"-"& @YEAR &" "& @HOUR &":"& @MIN &" --Work Memory:"& $MEM[0] & _        " --Peak Memory:"& $MEM[1])	  Sleep (10000)   ;ElseIf $MEM[0] > 700000000 Then	  ;ProcessClose($PID)	  ;ControlSend("Cube Server Loop Utility", "", "", "q {enter}")	  ;Sleep (10000)   EndIfEndIf       If @HOUR = $HotHour And @MIN = $HotMin Then    Local $PID = ProcessExists("Server.exe")	  If $PID Then		 Local $MEM = ProcessGetStats($PID, 0)		 FileWriteLine(@ScriptDir & "\RestartLog.txt", @MON &"-"& @MDAY &"-"& @YEAR &" "& @HOUR &":"& @MIN &" --Work Memory:"& $MEM[0] & _		 " --Peak Memory:"& $MEM[1] &" Restart Requested by CWServerUtility Script")	     ;ControlSend("Cube Server Loop Utility", "", "", "q {enter}")		 ProcessClose($PID)	  EndIf   Sleep (70000)    EndIfSleep (500)WEnd  
AutoIT Script (Stand Alone . No Batch File Required)
#include <Date.au3>#include <Process.au3>;User VariablesLocal $g_IP = "127.0.0.1" ;IP Restart Command Should Listen OnLocal $g_Port = "54321" ;Port Restart Command Should Listen OnLocal $RestartCode = "Restart" ;Code to Reset Server;End User VariablesLocal $HotMin = "01"If Not IsDeclared("sInputBoxAnswer") Then Local $sInputBoxAnswer$sInputBoxAnswer = InputBox("Cube World Auto Restart and Daily Restart","What hour of the day do you want to Restart?" & @CRLF & @CRLF & "Note:  Please use a number value between 00 and 23" & @CRLF & "           00 means midnight, 14 would be 2pm, etc." & @CRLF,"10", " M2","400","180","350","350","60")SelectCase @Error = 0 ;OK - The string returned is valid   Local $HotHour = $sInputBoxAnswerCase @Error = 1 ;The Cancel button was pushed   Exit     ; finishedCase @Error = 2 ;Timeout Reached   Local $HotHour = "10"Case @Error = 3 ;The InputBox failed to open   Exit     ; finishedEndSelectFunc _TCP_Server_ClientIP($hSocket)   Local $pSocketAddress, $aReturn   $pSocketAddress = DllStructCreate("short;ushort;uint;char[8]")   $aReturn = DllCall("ws2_32.dll", "int", "getpeername", "int", $hSocket, "ptr", DllStructGetPtr($pSocketAddress), "int*", DllStructGetSize($pSocketAddress))   If @error Or $aReturn[0] <> 0 Then Return $hSocket	  $aReturn = DllCall("ws2_32.dll", "str", "inet_ntoa", "int", DllStructGetData($pSocketAddress, 3))   If @error Then Return $hSocket	  $pSocketAddress = 0   Return $aReturn[0] EndFunc ;==>_TCP_Server_ClientIP; Start The TCP ServicesTCPStartup()Local $MainSocket = TCPListen($g_IP, $g_Port, 100)If $MainSocket = -1 Then Exitwhile True	if WinExists("Server.exe") Then		ControlSend("Server.exe", "", "", "{enter}")		Sleep (10000)	EndIfLocal $ConnectedSocket = TCPAccept($MainSocket)If $ConnectedSocket >= 0 Then;TrayTip("Connected","Someone connected to server.",3)$Count = 0While $Count < 30$RECV = TCPRecv($ConnectedSocket,512)   If $RECV = $RestartCode Then   Local $PID = ProcessExists("Server.exe") ; Will return the PID or 0 if the process isn't found.   	  If $PID Then		 $IP = _TCP_Server_ClientIP($ConnectedSocket)		 Local $MEM = ProcessGetStats($PID, 0)		 FileWriteLine(@ScriptDir & "\RestartLog.txt", @MON &"-"& @MDAY &"-"& @YEAR &" "& @HOUR &":"& @MIN &" --Work Memory:"& $MEM[0] & _		 " --Peak Memory:"& $MEM[1] &" Restart Requested by Remote Host: "& $IP)		 ProcessClose($PID)		 Sleep (10000)		 ExitLoop	  EndIf   EndIf$Count += 1Sleep (1000)WEndIf $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket)EndIfLocal $PID = ProcessExists("Server.exe")If $PID = 0 Then   Run(@ComSpec & " /c " & 'Server.exe', @ScriptDir)   Sleep (70000)Else    Local $MEM = ProcessGetStats($PID, 0)   If $MEM[0] > 600000000 Then	  FileWriteLine(@ScriptDir & "\ExcessiveMemoryLog.txt", @MON &"-"& @MDAY &"-"& @YEAR &" "& @HOUR &":"& @MIN &" --Work Memory:"& $MEM[0] & _        " --Peak Memory:"& $MEM[1])	  Sleep (10000)   ;ElseIf $MEM[0] > 700000000 Then	  ;ProcessClose($PID)	  ;Sleep (10000)   EndIfEndIf       If @HOUR = $HotHour And @MIN = $HotMin Then    Local $PID = ProcessExists("Server.exe")	  If $PID Then		 Local $MEM = ProcessGetStats($PID, 0)		 FileWriteLine(@ScriptDir & "\RestartLog.txt", @MON &"-"& @MDAY &"-"& @YEAR &" "& @HOUR &":"& @MIN &" --Work Memory:"& $MEM[0] & _		 " --Peak Memory:"& $MEM[1] &" Restart Requested by CWServerUtility Script")		 ProcessClose($PID)	  EndIf   Sleep (10000)    EndIfSleep (500)WEnd 
Remote Server Restart AutoIT Script (Not required for either utility)
    ; Start The TCP Services    ;==============================================    TCPStartup()   ; Set Some reusable info   ;--------------------------   Local $ConnectedSocket, $szData   ; Set $szIPADDRESS to wherever the SERVER is. We will change a PC name into an IP Address   ;   Local $szServerPC = @ComputerName   ;Local $szIPADDRESS = "127.0.0.1" ;@IPAddress1   ;Local $szIPADDRESS = TCPNameToIP("gamercide.org")   Local $nPORT = 54321 ;Change If you change Server PortIf Not IsDeclared("sInputBoxAnswer") Then Local $sInputBoxAnswer$sInputBoxAnswer = InputBox("Cube World Remote Restart","What is the IP of the Server you wish to Restart?" & @CRLF & @CRLF & "Note:  Please use IPv4 Only!" & @CRLF & "    Example: 127.0.0.1" & @CRLF,"127.0.0.1", " ","400","180","350","350","60")SelectCase @Error = 0 ;OK - The string returned is valid   Local $szIPADDRESS = $sInputBoxAnswerCase @Error = 1 ;The Cancel button was pushed   Exit     ; finishedCase @Error = 2 ;Timeout Reached   Local $szIPADDRESS = "127.0.0.1"Case @Error = 3 ;The InputBox failed to open   Exit     ; finishedEndSelect    ; Initialize a variable to represent a connection    ;==============================================    $ConnectedSocket = -1    ;Attempt to connect to SERVER at its IP and PORT 54321    ;=======================================================    $ConnectedSocket = TCPConnect($szIPADDRESS, $nPORT)    ; If there is an error... show it    If @error Then        MsgBox(4112, "Error", "TCPConnect failed with WSA error: " & @error)        ; If there is no error loop an inputbox for data        ;   to send to the SERVER.    Else        ;Loop forever asking for data to send to the SERVER        While 1            ; InputBox for data to transmit            $szData = InputBox("Reset The CW Server", @LF & @LF & "Enter the code to Reset The CW Server:")            ; If they cancel the InputBox or leave it blank we exit our forever loop            If @error Or $szData = "" Then ExitLoop            ; We should have data in $szData... lets attempt to send it through our connected socket.            ; convert AutoIt native UTF-16 to UTF-8            TCPSend($ConnectedSocket, StringToBinary($szData, 4))			ExitLoop            ; If the send failed with @error then the socket has disconnected            ;----------------------------------------------------------------            If @error Then ExitLoop        WEnd	 EndIfIf $ConnectedSocket <> -1 Then TCPCloseSocket($ConnectedSocket)TCPShutdown()

Click here to view the article

Link to comment
Share on other sites

Well, turns out Cube World likes to crash hard and leave a nice windows message that won't close.  Here's an Autoit script to close it automatically. Need to run it along side the Cube World Utility to make sure your server will restart unattended.

Local $tvHandle = 0while True	$tvHandle = WinWaitActive("Server.exe")	if Not ($tvHandle = 0) Then		Send("{Enter}")	EndIfWEnd
Link to comment
Share on other sites

I updated the AutoIT script and added a stand alone for those who don't want to use the batch.  This is a trial run with the AutoIT script. It will be closing the server anytime memory usage goes above 400MB. This seems to be when the crashes are occuring.

 

When running the batch and AutoIT scripts together, use the AutoIT exe to start the server and quit through the command window. The AutoIT starts the batch file and the batch file kills the AutoIT scripts.  The AutoIT prompt will automatically close after 60 seconds and start with a default of 10am.

Link to comment
Share on other sites

Ok, so the automatic restart when the memory limit was made wasn't working. The game definitely has a problem when memory usage gets too high, but it isn't consistent enough. There is no limit I can set that doesn't seem to sometimes close the server when it doesn't need to.  So, I removed that option, and I am simply logging memory usage when it rises above 600MB.  I left the code commented out that would close the server at a certain memory limit for anyone who wants to use it.

 

Since there is no reliable way to detect a locked up server I decided to go the remote restart route.  There is now a separate file you can download that allows the server to be remotely restarted.  I suggest you download AutoIT and edit the source files to your liking. It would be wise to change the port and password required to reset the server remotely. By default the Port is 54321 and Password is Restart.

Link to comment
Share on other sites

Please sign in to comment

You will be able to leave a comment after signing in



Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...