C# 远程服务器 创建、修改、删除 应用程序池 网站

2021-05-13 23:27

阅读:603

标签:++   period   remote   检测   ini   model   mic   always   first   

首先 C# 操作 站点 需要 引用Microsoft.Web.Administration.dll 文件,创建站点我们一般需要 远程服务的IP,网站名称、端口、物理路径;这里默认网站名称和应用程序池名称一致。

应用程序池默认不启动,应为刚创建站点是没有对应真实的物理文件,修改 队列长度、启动模式、回收时间、最大工作进程, 以及日志路径。修改的时候如果修改站点物理路径的话,我们需要把文件 从旧得目录拷贝到新的目录下,删除站点就比较简单了。

但是站点应用程序池的停止 和启动就比较难搞了,不是调用stop后就马上能停止的,我们需要一个检测状态的机制以及重试机制,如果没有停止 就等待一段时间,因为只有应用程序池完全停止后我们在可以拷贝文件到应用程序目录下;启动也是一样的需要一个 等待 和重试的机制。相关code如下:

  #region IIS 操作
        /// 
        /// 创建IIS site 
        /// 
        /// 服务器IP
        /// site 名称
        /// site端口
        /// site地址
        void CreateWebSite(string serverIP, string webName, int port, string path)
        {
            using (ServerManager sm = ServerManager.OpenRemote(serverIP))
            {
                //创建应用程序池
                ApplicationPool appPool = sm.ApplicationPools.FirstOrDefault(x => x.Name == webName);
                if (appPool == null)
                {
                    appPool = sm.ApplicationPools.Add(webName);
                    appPool.AutoStart = false;

                    appPool.QueueLength = 10000;
                    appPool.StartMode = StartMode.AlwaysRunning;//启动模式
                    appPool.Recycling.PeriodicRestart.Time = new TimeSpan();//回收时间间隔
                    appPool.ProcessModel.IdleTimeout = new TimeSpan();//闲置超时
                    appPool.ProcessModel.MaxProcesses = 1;//最大工作进程数
                }
                //创建Site
                Site site = sm.Sites.FirstOrDefault(x => x.Name == webName);
                if (site == null)
                {
                    //检查远程文件夹是否存在 不存在创建
                    string remotePath = PathUtil.GetRemotePath(serverIP, path);
                    if (!Directory.Exists(remotePath))
                    {
                        Directory.CreateDirectory(remotePath);
                    }

                    site = sm.Sites.Add(webName, path, port);
                    site.ServerAutoStart = true;

                    site.Bindings[0].EndPoint.Port = port;
                    Application root = site.Applications["/"];
                    root.ApplicationPoolName = webName;
                    root.VirtualDirectories["/"].PhysicalPath = path;
                    root.SetAttributeValue("preloadEnabled", true); /*预加载*/

                    #region 修改日志路径
                    if (!string.IsNullOrEmpty(ConfigUtil.IISLog))
                    {
                        string remoteLog = PathUtil.GetRemotePath(serverIP, ConfigUtil.IISLog);
                        if (!Directory.Exists(remoteLog))
                        {
                            Directory.CreateDirectory(remoteLog);
                        }
                        site.LogFile.Directory = ConfigUtil.IISLog;
                        string failedLog = Path.Combine(ConfigUtil.IISLog, "FailedReqLogFiles");
                        if (!Directory.Exists(failedLog))
                        {
                            Directory.CreateDirectory(failedLog);
                        }
                        site.TraceFailedRequestsLogging.Directory = failedLog;
                    }
                    #endregion
                }
                sm.CommitChanges();
            }
        }

        /// 
        /// 修改IIS站点名 端口 和路径
        /// 
        /// 服务器IP
        /// 旧的名称
        /// 新的web名称
        /// 新的端口
        /// 新的路径
        void ModifyWebSite(string serverIP, string oldWebName, string newWebName, int newPort, string newPath)
        {
            using (ServerManager sm = ServerManager.OpenRemote(serverIP))
            {
                //修改应用程序池
                ApplicationPool appPool = sm.ApplicationPools.FirstOrDefault(x => x.Name == oldWebName);
                if (appPool != null && oldWebName != newWebName)
                {
                    appPool.Name = newWebName;
                }
                //修改Site
                Site site = sm.Sites.FirstOrDefault(x => x.Name == oldWebName);
                if (site != null)
                {
                    Application root = site.Applications["/"];
                    if (oldWebName != newWebName)
                    {
                        site.Name = newWebName;
                        root.ApplicationPoolName = newWebName;
                    }

                    int oldPort = site.Bindings[0].EndPoint.Port;
                    if (oldPort != newPort)
                    {
                        site.Bindings[0].EndPoint.Port = newPort;
                    }
                    string oldPath = root.VirtualDirectories["/"].PhysicalPath;
                    if (oldPath.ToLower() != newPath.ToLower())
                    {
                        string remoteOldPath = PathUtil.GetRemotePath(serverIP, oldPath);
                        string remoteNewPath = PathUtil.GetRemotePath(serverIP, newPath);
                        if (!Directory.Exists(remoteNewPath))
                        {
                            Directory.CreateDirectory(remoteNewPath);
                        }

                         //拷贝文件
                         CopyFiles(remoteOldPath, remoteNewPath);

                        if (Directory.Exists(remoteOldPath))
                        {
                            Directory.Delete(remoteOldPath, true);
                        }
                        root.VirtualDirectories["/"].PhysicalPath = newPath;
                    }
                }
                #region 修改日志路径
                if (!string.IsNullOrEmpty(ConfigUtil.IISLog))
                {
                    string remoteLog = PathUtil.GetRemotePath(serverIP, ConfigUtil.IISLog);
                    if (!Directory.Exists(remoteLog))
                    {
                        Directory.CreateDirectory(remoteLog);
                    }
                    site.LogFile.Directory = ConfigUtil.IISLog;
                    string failedLog = Path.Combine(ConfigUtil.IISLog, "FailedReqLogFiles");
                    if (!Directory.Exists(failedLog))
                    {
                        Directory.CreateDirectory(failedLog);
                    }
                    site.TraceFailedRequestsLogging.Directory = failedLog;
                }
                #endregion
                sm.CommitChanges();
            }
        }

        /// 
        /// 删除IIS 站点
        /// 
        /// 服务器地址
        /// 站点名
        void RemoveWebSite(string serverIP, string webName)
        {

            string path = string.Empty;
            using (ServerManager sm = ServerManager.OpenRemote(serverIP))
            {
                //删除应用程序池
                ApplicationPool appPool = sm.ApplicationPools.FirstOrDefault(x => x.Name == webName);
                if (appPool != null)
                {
                    //appPool.Stop();
                    sm.ApplicationPools.Remove(appPool);
                }
                //删除Site
                Site site = sm.Sites.FirstOrDefault(x => x.Name == webName);
                if (site != null)
                {
                    path = site.Applications["/"].VirtualDirectories["/"].PhysicalPath;
                    sm.Sites.Remove(site);
                }
                sm.CommitChanges();
            }
            //删除文件
            if (!string.IsNullOrEmpty(path))
            {
                string remotePath = PathUtil.GetRemotePath(serverIP, path);
                if (Directory.Exists(remotePath))
                {
                    Directory.Delete(remotePath, true);
                }
            }
        }

        /// 
        /// 在服务器上检查端口是否被其他站点使用
        /// 
        /// 服务器地址
        /// 端口号
        /// 站点名
        /// 
        bool CheckPortIsUsed(string webIP, string webName, int webPort)
        {
            bool exist = false;
            try
            {
                using (ServerManager sm = ServerManager.OpenRemote(webIP))
                {
                    List sites = sm.Sites.ToList();
                    foreach (Site site in sites)
                    {
                        foreach (var item in site.Bindings)
                        {
                            if (item.EndPoint != null && item.EndPoint.Port == webPort && site.Name != webName)
                            {
                                exist = true;
                                break;
                            }
                        }//end for Bindings
                    }//end for Site
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return exist;
        }

        /// 
        /// 停止或启动应用程序池
        /// 
        /// 远程服务器IP
        /// 应用程序池名称集合
        /// true 停止 false 启动
        public void StopAndStartAppPool(string serverIP, string poolName, bool stop = true)
        {
            using (ServerManager sm = ServerManager.OpenRemote(serverIP))
            {
                ApplicationPool pool = sm.ApplicationPools.FirstOrDefault(x => x.Name == poolName);
                if (pool != null)
                {
                    StopAndStartAppPool(pool, stop);
                    if (stop)
                    {
                        WaiteAppPoolState(pool, ObjectState.Stopped);
                    }
                }
            }
        }

        /// 
        /// 停止或启动应用程序池
        /// 
        /// 应用程序池对象
        /// 是否是停止
        void StopAndStartAppPool(ApplicationPool pool, bool stop = true)
        {
            Action act = () =>
            {
                ObjectState poolSate = pool.State;
                if (stop && (poolSate == ObjectState.Starting || poolSate == ObjectState.Started))
                {
                    //如果当前应用程序池是启动或者正在启动状态,调用停止方法
                    pool.Stop();
                }
                if (!stop && (poolSate == ObjectState.Stopped || poolSate == ObjectState.Stopping))
                {
                    pool.Start();
                }
            };
            int retryCount = 0;
            int maxCount = 4;
            while (pool != null && retryCount  maxCount)
            {
                try
                {
                    act();
                    break;
                }
                catch (Exception ex)
                {
                    retryCount++;
                    if (retryCount == maxCount)
                    {
                        throw new Exception($"{(stop ? "停止" : "启动")}启动应用程序池{pool.Name}出错{ex.Message}");
                    }
                    Thread.Sleep(1000 * 30);
                }
            }//end while
        }

        /// 
        /// 检查引用程序池的状态
        /// 
        /// 程序池
        /// 状态
        void WaiteAppPoolState(ApplicationPool pool, ObjectState state)
        {
            int times = 0;
            while (pool.State != state && times 50 /*5分钟*/)
            {
                //检查应用程序池是否已经停止
                Thread.Sleep(1000 * 10);
                times++;
            }
        }

        /// 
        /// 获取应用程序池 和站点的状态
        /// 
        /// 服务器IP
        /// 站点名称
        /// 
        string GetWebState(string serverIP, string webName)
        {
            ObjectState poolState = ObjectState.Unknown;
            ObjectState siteState = ObjectState.Unknown;
            using (ServerManager sm = ServerManager.OpenRemote(serverIP))
            {
                //应用程序池
                ApplicationPool appPool = sm.ApplicationPools.FirstOrDefault(x => x.Name == webName);
                if (appPool != null)
                {
                    poolState = appPool.State;
                }

                //Site
                Site site = sm.Sites.FirstOrDefault(x => x.Name == webName);
                if (site != null)
                {
                    siteState = site.State;
                }
            }
            return $"{poolState.ToString()} | {siteState.ToString()}";
        }
        #endregion

 

 public class ConfigUtil
    {
        static string _dotNetPath = string.Empty;
        public static string DotNetPath
        {
            get
            {
                if (string.IsNullOrEmpty(_dotNetPath))
                {
                    string sysDisk = Environment.SystemDirectory.Substring(0, 3);
                    _dotNetPath = sysDisk + @"WINDOWS\Microsoft.NET\Framework\v4.0.30319\InstallUtil.exe";//因为当前用的是4.0的环境  
                }
                return _dotNetPath;
            }
        }

        static string _iisLog = string.Empty;
        public static string IISLog
        {
            get
            {
                if (string.IsNullOrEmpty(_iisLog))
                {
                    _iisLog = ConfigurationManager.AppSettings["IISLog"];
                }
                return _iisLog;
            }
        }
    }

 

C# 远程服务器 创建、修改、删除 应用程序池 网站

标签:++   period   remote   检测   ini   model   mic   always   first   

原文地址:http://www.cnblogs.com/majiang/p/7533840.html


评论


亲,登录后才可以留言!