def get_workers(mem_type=MEM_TYPES[0], mem_unit="KB"): """ returns a list of Worker objects """ workers = [] cmd = "sc query w3svc" output = config.run(cmd) if not "RUNNING" in output: config.run("sc start w3svc") cmd = "%s list wps" % config.APP_CMD proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) output = proc.communicate()[0] if type(output) == bytes: output = output.decode(encoding="UTF-8") if proc.returncode != 0: if "ERROR" in output: raise Exception("Either the WAS service is down or " "You need elevated permissions.") else: return [] for line in output.splitlines(): if len(line) > 5: pid = int(line.split('"')[1]) worker = Worker( poolname=line[line.find(":") + 1 : -1], pid=pid, mem=get_mem(pid, mem_type, mem_unit), mem_type=mem_type ) workers.append(worker) return workers
def get_workers(mem_type=MEM_TYPES[0], mem_unit='KB'): """ returns a list of Worker objects """ workers = [] cmd = "sc query w3svc" output = config.run(cmd) if not "RUNNING" in output: config.run("sc start w3svc") cmd = "%s list wps" % config.APP_CMD proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) output = proc.communicate()[0] if type(output) == bytes: output = output.decode(encoding='UTF-8') if proc.returncode != 0: if "ERROR" in output: raise Exception("Either the WAS service is down or "\ "You need elevated permissions.") else: return [] for line in output.splitlines(): if len(line) > 5: pid = int(line.split('"')[1]) worker = Worker(poolname=line[line.find(':')+1:-1],\ pid=pid,\ mem=get_mem(pid, mem_type, mem_unit),\ mem_type=mem_type) workers.append(worker) return workers
def delete(name): """ deletes a site given its name """ if not exists(name): print("The site '%s' does not exist." % name) return cmd = "%s delete site \"%s\"" % (config.APP_CMD, name) config.run(cmd)
def modify_binding(name, protocol, port, ip='', host=''): """ remove one or more bindings from an iis site Parameters: - name: site name - protocol: Examples: http, https, net.pipe, net.tcp, net.msmq, msmq.formatname, ftp - port: int - the port number - ip: the ip address - default = '' - host: the host assigned - default = '' """ cmd = "%s set site %s /bindings.[protocol='%s',bindingInformation='%s:%i:%s']"\ % (config.APP_CMD, name, protocol, host, int(port), ip) config.run(cmd)
def register_asp(): """ installs and registers asp.net on iis """ framework_dir = "%s\\Framework"\ % (config.NET_DIR, os.getenv('SYSTEMDRIVE')) versions = ["v2.0.50727", "v4.0.30319"] for ver in versions: aspnet_regiis = os.path.join(framework_dir, ver, 'aspnet_regiis.exe') if os.path.exists(aspnet_regiis): cmd = "%s -ir" % aspnet_regiis config.run(cmd) else: print("Could not register %s because the file is missing: %s"\ % (ver, aspnet_regiis)) config.run("%s /Online /Enable-Feature /all /FeatureName:IIS-ASPNET45" % config.DISM)
def get_status(): """ gets the iis status {stopped, running} """ output = config.run('iisreset /status') if "Running" in output: return "running" else: return "stopped"
def get_mem(pid, mem_type=MEM_TYPES[0], mem_unit='KB'): """ given the process id and the type of memory this method retrieves the memory usage in bytes and returns it as an integer """ if mem_type == MEM_TYPES[0]: cmd = "%s path Win32_PerfRawData_PerfProc_Process get IDProcess,WorkingSetPrivate"\ % config.WMIC elif mem_type == MEM_TYPES[1]: cmd = "%s path win32_process get ProcessId,WorkingSetSize"\ % config.WMIC else: raise Exception("Invalid memory type: %s" % mem_type) output = config.run(cmd) for line in output.splitlines(): line = line.strip() ind = line.find(' ') if ind > 0: pidstr = line[0:ind].strip() if pidstr.isdigit() and\ pid == int(pidstr): mem = int(line[ind+1:].strip()) if mem_unit == 'KB': mem /= 1024.0 if mem_unit == 'MB': mem = mem / 1024.0 / 1024.0 return mem raise Exception('The pid was not found: %i' % pid)
def get_mem(pid, mem_type=MEM_TYPES[0], mem_unit="KB"): """ given the process id and the type of memory this method retrieves the memory usage in bytes and returns it as an integer """ if mem_type == MEM_TYPES[0]: cmd = "%s path Win32_PerfRawData_PerfProc_Process get IDProcess,WorkingSetPrivate" % config.WMIC elif mem_type == MEM_TYPES[1]: cmd = "%s path win32_process get ProcessId,WorkingSetSize" % config.WMIC else: raise Exception("Invalid memory type: %s" % mem_type) output = config.run(cmd) for line in output.splitlines(): line = line.strip() ind = line.find(" ") if ind > 0: pidstr = line[0:ind].strip() if pidstr.isdigit() and pid == int(pidstr): mem = int(line[ind + 1 :].strip()) if mem_unit == "KB": mem /= 1024.0 if mem_unit == "MB": mem = mem / 1024.0 / 1024.0 return mem raise Exception("The pid was not found: %i" % pid)
def is_port_taken(port): """ returns a boolean indicating whether the port is being used by any iis site Parameters: - port: int """ cmd = "%s list sites" % config.APP_CMD output = config.run(cmd) return "/*:%s:," % port in output
def exists(name): """ given the site name, returns whether the site already exists """ cmd = "%s list sites" % config.APP_CMD output = config.run(cmd) for line in output.splitlines(): if line.split('"')[1] == name: return True return False
def is_running(name): """ returns a boolean indicating whether the site is config.running """ cmd = "%s list sites /state:Started" % config.APP_CMD output = config.run(cmd) for line in output.splitlines(): if line.split('"')[1] == name: return True return False
def create(name, port, path, pool_name, protocol="http", site_id=None, ip='', host=''): """ creates a new iis site Parameters: - name: site name - port: port number - path: the directory where your web app is - pool_name: pool name to associate with the site - protocol (optional): http, https - site_id (optional): the site id to associate with the new site """ if exists(name): print("The site '%s' already exists." % name) return if is_port_taken(port): raise Exception("An iis site is already using the port: %i" % port) if not is_port_available(port): raise Exception("A program is already using the port: %i" % port) if not pool.exists(pool_name): pool.create(pool_name) for iter in range(5): # wait a bit if pool.exists(pool_name): break time.sleep(1) cmd = "%s add site /name:\"%s\" /physicalPath:\"%s\" /bindings:%s/%s:%i:%s"\ % (config.APP_CMD, name, path, protocol, host, port, ip) if site_id: cmd = "%s /id:%i" % (cmd, site_id) config.run(cmd) config.run("%s set app \"%s/\" /applicationPool:\"%s\""\ % (config.APP_CMD, name, pool_name)) for iter in range(5): # wait a bit if exists(name): break time.sleep(1)
def get_bindings(name): """ returns a list of bindings Parameters: name: site name """ cmd = "%s list sites" % config.APP_CMD output = config.run(cmd, errMsg="You need elevated permissions.") for line in output.splitlines(): parts = line.split('bindings:') if name in parts[0]: bindings = parts[1].split(',state')[0] return bindings.split(',') return []
def create(name, port, path, pool_name, protocol="http", site_id=None, ip='', host=''): """ creates a new iis site Parameters: - name: site name - port: port number - path: the directory where your web app is - pool_name: pool name to associate with the site - protocol (optional): http, https - site_id (optional): the site id to associate with the new site """ if exists(name): print("The site '%s' already exists." % name) return if is_port_taken(port): raise Exception("An iis site is already using the port: %i" % port) if not is_port_available(port): raise Exception("A program is already using the port: %i" % port) if not pool.exists(pool_name): pool.create(pool_name) for iter in range(5):# wait a bit if pool.exists(pool_name): break time.sleep(1) cmd = "%s add site /name:\"%s\" /physicalPath:\"%s\" /bindings:%s/%s:%i:%s"\ % (config.APP_CMD, name, path, protocol, host, port, ip) if site_id: cmd = "%s /id:%i" % (cmd, site_id) config.run(cmd) config.run("%s set app \"%s/\" /applicationPool:\"%s\""\ % (config.APP_CMD, name, pool_name)) for iter in range(5):# wait a bit if exists(name): break time.sleep(1)
def get_pool_names(): """ returns a list of application pool names """ cmd = "%s list apppool" % config.APP_CMD output = config.run(cmd, errMsg="You need elevated permissions.") return [str(line.split('"')[1]) for line in output.splitlines()]
def stop(name): """ stops the site """ if is_running(name): cmd = "%s stop site \"%s\"" % (config.APP_CMD, name) config.run(cmd)
def start(name): """ starts the site """ if not is_running(name): cmd = "%s start site \"%s\"" % (config.APP_CMD, name) config.run(cmd)
def install(packages=None): """ installs iis Parameters -------- packages: list. The iis features (package names) """ # for windows vista and up (windows 7, windows 8, windows server 2012): dism_pkgs = ["IIS-WebServerRole", "IIS-WebServer", "IIS-CommonHttpFeatures",\ "IIS-Security", "IIS-RequestFiltering", "IIS-StaticContent",\ "IIS-DefaultDocument", "IIS-DirectoryBrowsing", "IIS-HttpErrors",\ "IIS-HttpRedirect", "IIS-WebDAV", "IIS-ApplicationDevelopment",\ "IIS-WebSockets", "IIS-ApplicationInit", "IIS-NetFxExtensibility",\ "IIS-NetFxExtensibility45", "IIS-ISAPIExtensions", "IIS-ISAPIFilter",\ "IIS-ASPNET", "IIS-ASPNET45", "IIS-ASP", "IIS-CGI", "IIS-ServerSideIncludes",\ "IIS-HealthAndDiagnostics", "IIS-HttpLogging", "IIS-LoggingLibraries",\ "IIS-RequestMonitor", "IIS-HttpTracing", "IIS-CustomLogging",\ "IIS-ODBCLogging", "IIS-CertProvider", "IIS-BasicAuthentication",\ "IIS-WindowsAuthentication", "IIS-DigestAuthentication",\ "IIS-ClientCertificateMappingAuthentication", "IIS-IISCertificateMappingAuthentication",\ "IIS-URLAuthorization", "IIS-IPSecurity", "IIS-Performance", "IIS-HttpCompressionStatic",\ "IIS-HttpCompressionDynamic", "IIS-WebServerManagementTools", "IIS-ManagementConsole",\ "IIS-LegacySnapIn", "IIS-ManagementScriptingTools", "IIS-ManagementService",\ "IIS-IIS6ManagementCompatibility", "IIS-Metabase", "IIS-WMICompatibility",\ "IIS-LegacyScripts", "IIS-FTPServer", "IIS-FTPSvc", "IIS-FTPExtensibility",\ "WAS-WindowsActivationService", "WAS-ProcessModel", "WAS-NetFxEnvironment",\ "WAS-ConfigurationAPI", "IIS-HostableWebCore"] professional_pkg = "IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;IIS-DirectoryBrowsing;"\ "IIS-HttpErrors;IIS-HttpRedirect;IIS-ApplicationDevelopment;IIS-ASPNET;IIS-NetFxExtensibility;IIS-ASP;IIS-CGI;"\ "IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-ServerSideIncludes;IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;"\ "IIS-RequestMonitor;IIS-HttpTracing;IIS-CustomLogging;IIS-ODBCLogging;IIS-Security;IIS-BasicAuthentication;"\ "IIS-WindowsAuthentication;IIS-DigestAuthentication;IIS-ClientCertificateMappingAuthentication;"\ "IIS-IISCertificateMappingAuthentication;IIS-URLAuthorization;IIS-RequestFiltering;IIS-IPSecurity;"\ "IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;IIS-WebServerManagementTools;"\ "IIS-ManagementConsole;IIS-ManagementScriptingTools;IIS-ManagementService;IIS-IIS6ManagementCompatibility;"\ "IIS-Metabase;IIS-WMICompatibility;IIS-LegacyScripts;IIS-LegacySnapIn;IIS-FTPPublishingService;IIS-FTPServer;"\ "IIS-FTPManagement;WAS-WindowsActivationService;WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI" premium_pkg = "IIS-WebServerRole;IIS-WebServer;IIS-CommonHttpFeatures;IIS-StaticContent;IIS-DefaultDocument;"\ "IIS-DirectoryBrowsing;IIS-HttpErrors;IIS-HttpRedirect;IIS-ApplicationDevelopment;IIS-ASPNET;"\ "IIS-NetFxExtensibility;IIS-ASP;IIS-CGI;IIS-ISAPIExtensions;IIS-ISAPIFilter;IIS-ServerSideIncludes;"\ "IIS-HealthAndDiagnostics;IIS-HttpLogging;IIS-LoggingLibraries;IIS-RequestMonitor;IIS-HttpTracing;"\ "IIS-CustomLogging;IIS-Security;IIS-BasicAuthentication;IIS-URLAuthorization;IIS-RequestFiltering;"\ "IIS-IPSecurity;IIS-Performance;IIS-HttpCompressionStatic;IIS-HttpCompressionDynamic;"\ "IIS-WebServerManagementTools;IIS-ManagementConsole;IIS-ManagementScriptingTools;IIS-ManagementService;"\ "IIS-IIS6ManagementCompatibility;IIS-Metabase;IIS-WMICompatibility;IIS-LegacyScripts;IIS-LegacySnapIn;"\ "WAS-WindowsActivationService;WAS-ProcessModel;WAS-NetFxEnvironment;WAS-ConfigurationAPI" if is_older_than_2008r2(): if not packages: packages = ["Web-Server"] for pkg in packages: try: config.run("%s -install %s" % (config.SERVER_MGR_CMD, pkg)) print("Installed %s -allSubFeatures " % pkg) except Exception as ex: if "NoChange" in str(ex): print("%s is already installed." % pkg) else: raise Exception(str(ex)) elif config.DISM: if not packages: packages = dism_pkgs for pkg in packages: try: cmd = "%s /online /Enable-Feature /FeatureName:%s"\ % (config.DISM, pkg) if 'Windows-post2008Server-6' in platform.platform():# windows8 cmd = "%s /All" % cmd config.run(cmd) print("Installed %s" % pkg) except: print("Failed to install %s" % pkg) elif packages: if type(packages) == list: packages_str = ";".join(packages) print("Installing %s" % packages_str) config.run("start /w pkgmgr /iu:%s" % packages_str) else: print("Installing %s" % professional_pkg) cmd = "start /w pkgmgr /iu:%s" % professional_pkg proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) proc.wait() if proc.returncode != 0: cmd = "start /w pkgmgr /iu:%s" % premium_pkg proc = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) proc.wait() if proc.returncode != 0: raise Exception("Failed to install some iis packages.")
def start(): """ starts iis """ if get_status() == "stopped": config.run('iisreset /start')
def stop(): """ stops iis """ if get_status() == "running": config.run('iisreset /stop')
def get_site_names(): """ returns a list of site names """ cmd = "%s list sites" % config.APP_CMD output = config.run(cmd, errMsg="You need elevated permissions.") return [str(line.split('"')[1]) for line in output.splitlines()]
def iisreset(): """ resets iis """ config.run('iisreset')