0

Use RegEx In TC Admin With Iron Python

Over the last few years of working with TC Admin I’ve come to enjoy using Iron Python.  However, it seems to be a feature of TC Admin that is hardly ever used.  I find this a bit surprising due to the amount of power it gives you in your custom scripts.  Not only do you get access to Python itself (without the standard library) you also get access to the .NET and TC Admin APIs.  This allows you to accomplish many things that you cannot do using batch scripts alone.

For this post we’ll look at using Regular Expressions for find and replace operations directly in TC Admin scripts.

Doing find and replaces on game servers is extremely common for automation.  Things such as inserting the services IP address into a config is a daily need. However, most GSPs do it in different ways.  Some use external exe files, while others go as far to include Perl in their game server files.

Using Iron Python directly within TC Admin means you can do it with no external tools.

For this example we’ll look replacing the bind address in the my.ini file for a MySQL server.

from System.Text.RegularExpressions import Regex
from System.String import Format
from System.IO import File

myini = File.ReadAllText("my.ini")

rgx = Regex("bind-address = .*")
myini = rgx.Replace(myini, Format('bind-address = "{0}"', ThisService.IpAddress))

File.WriteAllText("my.ini", myini)

Line 1 – 3: We’re importing several .NET classes to use in the script. First, we import the Regex class. We then import the String Format class to make it easier to manipulate strings. Finally, we import the File class for manipulating files.
Line 5: We open up the file we wish to do the find and replace on and save it to a variable.
Line 7: We define the Regex Patter we wish to use.
Line 8: We call the Regex classes Replace method. We target the my.ini file we opened and use string formatting to insert the server’s IP address into the string.
Line 10: We write our modified file out to the physical file.

That’s all there is to it.  As you can see it’s very simply to do find and replace operations, with full Regex support, directly in TC Admin scripts without the need for external tools.

matt

Leave a Reply

Your email address will not be published. Required fields are marked *