Restart an IIS Site from a BAT File Using JAVA Servlet
we have designed an architecture where a batch file will restart an IIS site and the batch file will initiate to run using a Java Servlet deployed in a tomcat server.
Architecture Flow Diagram
Synopsis
Our aim is to restart an IIS Site residing in instance group having dynamic IP ranges. It will be pretty hard for a user to identify a dynamic IP created from a Load Balancer. So we have designed an architecture where a batch file will restart an IIS site and the batch file will initiate to run using a Java Servlet deployed in a tomcat server, and that servlet will be hit by another servlet residing in another server which will fetch the dynamic URLs from the instance group and therefore the batch file will be initiated and hence the IIS site will get restarted.
Step 1:
1.1 Create Server 1: instance-windows
Please follow the link below- https://cloud.google.com/compute/docs/instances/create-start-instance
1.2 Install XAMPP
Download your XAMPP installation here. After installation start the XAMPP Control panel (right click on tray icon for XAMPP and choose show/hide). Start the Apache and MySQL service. PID(s) and Port(s) should show a number now indicating the services are listening at the ports shown.
1.3 Configure classpaths
To set the JAVA_HOME variable:
Locate your Java installation directory. If you didn't change the path during installation, it'll be something like C:\Program Files\Java\jdk1.8.0_65
You can also type where java at the command prompt.
Do one of the following:
Windows 7 – Right click My Computer and select Properties > Advanced
Windows 8 – Go to Control Panel > System > Advanced System Settings
Windows 10 – Search for Environment Variables then select Edit the system environment variables
Click the Environment Variables button.
Under System Variables, click New.
In the Variable Name field, enter either:
JAVA_HOME if you installed the JDK (Java Development Kit)
or
JRE_HOME if you installed the JRE (Java Runtime Environment)
In the Variable Value field, enter your JDK or JRE installation path.
If the path contains spaces, use the shortened path name.
1.4 Create an IIS Site
To create a new Web site in Apache, you must set up a virtual host and configure the individual settings for the host. If you are using IIS, you can create a new Web site by translating the following terms to the IIS equivalents
Apache term | IIS term |
DocumentRoot | IIS Web Site Home Directory |
ServerName | IIS Host Header |
Listen | IIS IP Address and TCP Port |
To create a new Web site in IIS, follow these steps:
Log on to the Web server computer as an administrator.
Click Start, point to Settings, and then click Control Panel.
Double-click Administrative Tools, and then double-click Internet Services Manager.
Click Action, point to New, and then click Web Site.
After the Web Site Creation Wizard starts, click Next.
Type a description for the Web site.
This description is used internally to identify the Website in Internet Services Manager only. Select the IP address to use for the site. If you select All (unassigned), the Web site is accessible on all interfaces and all configured IP addresses.
7. Type the TCP port number to publish the site on.
8. Type the Host Header name (the real name that is used to access this site).
9. Click Next.
Either type the path to the folder that is holding the Web site documents or click Browse to select the folder, and then click Next. Select the access permissions for the Web site, and then click Next.
10. Click Finish.
1.5 Create a batch file which will restart the IIS Site created in step 1.4
1.5.1. Open a text editor
1.5.2. Copy the code:
cd C:\Windows\System32\inetsrv
.\appcmd stop site /site.name:<Website_name>
.\appcmd start site /site.name:<Wesite_name>
1.5.3. Save it as <filename>.bat
1.5.4. And keep the file in the same directory where your website files are residing.(in my case C:\\inetpub\\Website)
1.6 Deploy RunBatchWebServlet code into tomcat server
Start the server
Open tomcat manager
Deploy the WAR file exported from your IDE.
Code for RunBatchWebServlet:
import java.io.File; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class RunBatchWebServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response);
} protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File dir = new File("C:\\inetpub\\Website"); //File dir = new File("C:\\"); ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/C", "Start","start.bat"); pb.directory(dir); pb.start(); response.setContentType("text/html"); response.getWriter().println("Your site has been restarted..."); } } |
1.7 Hit the Servlet URL manually and test whether the IIS server is getting restarted or not.
URL will be: http://IP:8080/RunBatchWebServlet/
Step 2:
2.1 Create Server 2: instance-remote
Please follow the link below- https://cloud.google.com/compute/docs/instances/create-start-instance
2.2 Install XAMPP
Same as step 1.2
2.3 Configure classpaths
Same as step 1.3
Here we have to set another extra classpath which will make the identification where the GOOGLE_APPLICATION_CREDENTIALS will reside to do that open your server’s command prompt and type the command given below:
setx -mGOOGLE_APPLICATION_CREDENTIALS “path/to/your/credential.json”
Reboot your instance
2.4 Deploy FetchDynamicIP code into tomcat server
import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.HttpURLConnection; import java.net.MalformedURLException; import java.net.URL; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.http.HttpRequest; import com.google.api.client.http.HttpRequestInitializer; import com.google.api.client.http.HttpTransport; import com.google.api.client.http.javanet.NetHttpTransport; import com.google.api.client.json.JsonFactory; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.compute.Compute; import com.google.api.services.compute.ComputeScopes; import com.google.api.services.compute.model.AccessConfig; import com.google.api.services.compute.model.Instance; import com.google.api.services.compute.model.InstanceList; import com.google.api.services.compute.model.NetworkInterface; public class FetchDynamicIP extends HttpServlet { private static final long serialVersionUID = 1L; final String USER_AGENT = "Mozilla/5.0"; private static final JsonFactory jsonFactory = JacksonFactory.getDefaultInstance(); private static HttpTransport httpTransport = new NetHttpTransport(); static HttpRequestInitializer httpRequestInitializer = new HttpRequestInitializer() { @Override public void initialize(HttpRequest arg0) throws IOException { } };
public void startCompute() { GoogleCredential credential=null; try { credential = GoogleCredential.getApplicationDefault(httpTransport, jsonFactory); } catch (IOException e) { e.printStackTrace(); } if (credential.createScopedRequired()) { credential = credential.createScoped(ComputeScopes.all()); } Compute com= new Compute.Builder(httpTransport, jsonFactory, credential).setApplicationName("GCP-Test").build(); try { InstanceList instanceList = com.instances().list("gcp-test-178407", "asia-south1-c").execute(); for(int count = 0; count<instanceList.getItems().size(); count++) { Instance instance = instanceList.getItems().get(count); java.util.List<NetworkInterface> networkList=instance.getNetworkInterfaces(); for(int networkInterfaceCount=0;networkInterfaceCount<networkList.size();networkInterfaceCount++) { NetworkInterface networkInterface=networkList.get(networkInterfaceCount); java.util.List<AccessConfig> accessConfigList=networkInterface.get Access Configs(); for(int accessConfigCount=0;accessConfigCount<accessConfigList.size();accessConfigCount++) { AccessConfig accessConfig = accessConfigList.get(accessConfigCount); String natIP = accessConfig.getNatIP(); System.out.println(natIP); if(natIP != null && !String.valueOf(natIP).equals("35.200.17X.XX") && !String.valueOf(natIP).equals("35.192.21X.XXX") && !String.valueOf(natIP).equals("35.200.16X.XXX") && !String.valueOf(natIP).equals("35.244.2X.XX") && !String.valueOf(natIP).equals("35.244.1X.XX") && !String.valueOf(natIP).equals("35.188.8X.XX")) { String httpUrl = "http://"+natIP+":8080/RunBatchWebServlet"; System.out.println(httpUrl); try { URL url = new URL(httpUrl); HttpURLConnection connection = (HttpURLConnection) url.op |
2.5 Hit the Servlet URL and see whether it is fetching the URL generated in step 1.7 and check whether the IIS is getting restarted or not.
You will get URL: http://IP:8080/FetchDynamicIP/