Friday, 21 October 2016

Batch and Bash script

Scripting simple batch and bash script is by far the most time-saving thing any administrator can do.
These can also be useful to anyone that needs to repeat a task with only simple values change.

For example, let's say I want to start ten tomcat server at once on my desktop for testing.

Bash
for i in {80..90}; do docker run -d --name tomcat$i -p 80$i:8080 tomcat8.5/example; done

Batch
for /l %i in (80,1,90) do docker run -d --name tomcat%i -p 80%i:8080 tomcat8.5/example

I would now have ten tomcats named tomcat80 to tomcat90 with ports mapped 8080 to 8090 easy to remember and easy to create, this could be lxd or hyper-v guest, it is really down to if there is a batch or bash command for them.

It's also possible I could have used more than one for in the command line and had the port numbers and names created separately but for the moment this just an example, what I would like to focus on is how windows and Linux have some small changes between them even tho the code above does exactly the same thing.

So let's do another example, this time I'm going to ping a subnet and see what answers.

Bash
for i in {1..254}; do ping -c 1 192.168.0.$i |grep ttl; done >range.txt

Batch
for /L %i in (1,1,254) do ping -n 1 192.168.0.%i |find /i "ttl" >range.txt

So now we have done two example working with number how about with files, this could be a list of servers or just list of names.

Bash
for i in $(cat serverlist1.txt); do echo $i; done

Batch
for /f %i in (serverlist1.txt) do echo %i

What you might have noticed already is that while Bash doesn't care about the type and uses brackets and dollar signs to tell the type of data batch uses the backslash switch for file vs number ranges and no switch for just data.


Bash
for i in Mo Tu We Th Fr; do echo day$i; done

Batch
for %i in (Mo Tu We Th Fr) do echo %i

Now that you have the basics of the for command you can create loops on files ranges and text with easier, how you apply that to your work can be anything from running commands on more than one server or patching, checking up time memory usage available space the list goes on.

Setting up ssh on more than one server
ssh-keygen && for host in $(cat hosts.txt); do ssh-copy-id $host; done

For running commands on more than one server, however I recommend Ansible for farms
for host in $(cat hosts.txt); do ssh "$host" "$command" >"output.$host"; done

Patching windows servers
for /f %i in (c:\serverlist1.txt) do psexec -c -d \\%i Win2008R2SP1.exe /quiet /norestart /overwriteoem


Installing features

for /f %i in (c:\serverlist1.txt) do psexec -c \\%i ServerManagerCmd.exe -install Application-Server Hyper-V WAS -restart

Just to be clear yes I am using psexec in my examples and I have said you should migrate to Powershell before however this is a Batch vs Bash not Bash vs Powershell example.

No comments: