Matthew
Matthew

Reputation: 63

Replacing a string with a random number using awk

I am currently trying to create an script that will start a vpn server on a new IP range. I have multiple servers, so there is a possibility of conflict if the 2 servers are using the same range.

I would therefore like to randomise the IP range that the server is started on. I would ideally like to randomise the IP in the following way in the generated config file;

    ifconfig 10.xxx.yyy.1 255.255.255.248
    server 10.xxx.yyy.0 255.255.255.248

The shell I am using is quite restricted, so many utilities like od are not available to create random numbers. However awk is available, so I think this will be suitable. I have had a stab at creating a command which will replace xxx and yyy with a random number between 0 and 255 but I haven't succeeded. Can anyone help me with this?

    awk '{var = int(rand() * 256); var2 = int(rand() * 256);  gsub(/xxx/, var ); gsub(/yyy/, var2 ) ; print}' /tmp/vpn.conf

This command changes the values to

    ifconfig 10.125.248.1 255.255.255.248
    server 10.74.196.0 255.255.255.248

which is obviously not desirable as both of xxx and yyy should be the same, eg

    ifconfig 10.25.64.1 255.255.255.248
    server 10.25.64.0 255.255.255.248

Can anyone assist in having awk perform the intended function? Alternatively, any simplified random number scripts will also suffice, however I am not hopeful of this working due to the lack of shell utilities available.

Thanks in advance for any help!

Upvotes: 1

Views: 1783

Answers (1)

Dennis Williamson
Dennis Williamson

Reputation: 360153

Generate the random numbers in the BEGIN block.

awk 'BEGIN{var = int(rand() * 256); var2 = int(rand() * 256)}  {sub(/xxx/, var ); sub(/yyy/, var2 ) ; print}' /tmp/vpn.conf

Also, there's no reason to use gsub, just use sub since there's only one replacement per line of the particular pattern.

Upvotes: 3

Related Questions