예제 #1
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            string AnonymousUserName = "******" + Regex.Replace(ServerComment.Text, @"\.|-", "_");
            string AnonymousUserPass = Comm.Random(20);

            if (AnonymousUserName.Length > 20)
            {
                AnonymousUserName = AnonymousUserName.Substring(0, 20);
            }
            WinNT.User.Del(AnonymousUserName);
            WinNT.User.Add(AnonymousUserName, AnonymousUserPass);


            if (!Directory.Exists(Path.Text))
            {
                Directory.CreateDirectory(Path.Text);
                File.WriteAllText(Path.Text + "\\CrazyIIS.html", "hello html");
                File.WriteAllText(Path.Text + "\\CrazyIIS.asp", "<%=1+1%>..OK");
                File.WriteAllText(Path.Text + "\\CrazyIIS.aspx", "<%=1+1%>..OK");
            }


            DirectoryEntry dir = new DirectoryEntry("IIS://localhost/w3svc");

            List <Int32> AllWebSiteId = Comm.GetAllWebSiteID();
            string       NewWebSiteId = Comm.GetNewWebSiteID(AllWebSiteId);

            AllWebSiteId.Add(Convert.ToInt32(NewWebSiteId));

            DirectoryEntry web = dir.Children.Add(NewWebSiteId, "IIsWebServer");

            web.Properties["AuthFlags"].Value        = 0;
            web.Properties["ServerAutoStart"].Value  = true;
            web.Properties["ServerBindings"].Value   = ServerBindings.Text.Split(',');
            web.Properties["ServerComment"].Value    = ServerComment.Text;
            web.Properties["LogFileDirectory"].Value = LogFileDirectory.Text;

            web.CommitChanges();

            DirectoryEntry root = web.Children.Add("root", "IIsWebVirtualDir");

            root.Properties["Path"].Value = Path.Text;

            //root.Invoke("AppCreate", true);//创建应用程序

            root.Properties["EnableDirBrowsing"][0] = false;
            root.Properties["AccessExecute"][0]     = false;
            root.Properties["AccessWrite"][0]       = false;
            root.Properties["AccessRead"][0]        = true; //设置读取权限
            root.Properties["AccessScript"][0]      = true; //执行权限
            root.Properties["AuthFlags"].Value      = 1;    //0表示不允许匿名访问,1表示就可以3为基本身份验证,7为windows继承身份验证


            root.Properties["AnonymousUserName"].Value = AnonymousUserName;
            root.Properties["AnonymousUserPass"].Value = AnonymousUserPass;
            root.Properties["AppFriendlyName"].Value   = ServerComment.Text;
            root.Properties["AppPoolId"].Value         = AppPoolId.Text;
            root.Properties["AppIsolated"].Value       = 2;
            root.Properties["AppRoot"].Value           = string.Format("/LM/W3SVC/{0}/Root", NewWebSiteId);

            root.CommitChanges();

            if (hosts.Checked)
            {
                Comm.Write2hosts(("127.0.0.1," + ServerComment.Text + ",127.0.0.1,www." + ServerComment.Text).Split(','), false);
            }

            NTFS.ACL.Add(Path.Text, AnonymousUserName, FileSystemRights.FullControl);
            NTFS.ACL.Add(Path.Text, "NETWORK SERVICE", FileSystemRights.FullControl);
            MessageBox.Show("OK");
        }
예제 #2
0
        private void backgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
        {
            Stopwatch sp = new Stopwatch();

            sp.Start();
            WinNT.NetUser User = new WinNT.NetUser();
            Dictionary <string, string> AllUsers = new Dictionary <string, string>();

            string MetaBase = File.ReadAllText(Comm.MetaBasePath());

            #region 取得所有匿名用户并重新给他们密码
            {
                MatchCollection _AnonymousUserName = Regex.Matches(MetaBase, @"AnonymousUserName=""(.+?)""");
                for (int i = 0; i < _AnonymousUserName.Count; i++)
                {
                    Match item = _AnonymousUserName[i];
                    if (!AllUsers.ContainsKey(item.Groups[1].Value))
                    {
                        AllUsers.Add(item.Groups[1].Value, Comm.Random(i, 10));
                    }
                }
            }
            #endregion

            #region 改用户密码
            foreach (var item in AllUsers)
            {
                backgroundWorker2.ReportProgress(50, "正在修改用户" + item.Key + "的密码" + sp.ElapsedMilliseconds.ToString());

                User.UserChangePassword(item.Key, item.Value);
            }
            #endregion

            #region 更新网站的匿名用户密码
            {
                backgroundWorker2.ReportProgress(50, "将要 给网站添加匿名用户" + sp.ElapsedMilliseconds.ToString());

                IISConfig.Metabase metabase = new IISConfig.Metabase();
                metabase.OpenLocalMachine();

                IISConfig.IKey   key    = metabase.GetKeyFromPath("/LM/W3SVC");
                IISConfig.Record record = key.GetRecord(6021);

                //更新"/LM/W3SVC"的默认用户密码
                record.Data = AllUsers[key.GetRecord(6020).Data.ToString()];
                key.SetRecord(record);



                MatchCollection matchs = Regex.Matches(MetaBase, @"Location\s*=\s*""(/LM/W3SVC/\d+/root)""", RegexOptions.IgnoreCase);
                foreach (Match item in matchs)
                {
                    key = metabase.GetKeyFromPath(item.Groups[1].Value);
                    if (key.GetRecord(6020) != null)
                    {
                        //用户名存在时,设置密码
                        record.Data = AllUsers[key.GetRecord(6020).Data.ToString()];
                        key.SetRecord(record);
                    }
                    else
                    {
                        //用户名不存在时,删除密码
                        if (key.GetRecord(6021) != null)
                        {
                            key.DeleteRecord(6021);
                        }
                    }
                }



                backgroundWorker2.ReportProgress(50, "给网站添加匿名用户完成" + sp.ElapsedMilliseconds.ToString());
            }
            #endregion

            sp.Stop();
            backgroundWorker2.ReportProgress(100, "操作完成 共用时:" + sp.ElapsedMilliseconds / 1000 + "s");
        }
예제 #3
0
        private void btnBackUp_Click(object sender, EventArgs e)
        {
            if (!File.Exists(Comm.MetaBasePath()))
            {
                MessageBox.Show("配置文件不存在,没法备份,请确认您已经安装IIS");
                return;
            }

            string BackUpPath = txtBackUp.Text;

            if (!Path.IsPathRooted(BackUpPath))
            {
                BackUpPath = Path.Combine(Application.StartupPath, BackUpPath);
            }

            if (Directory.Exists(BackUpPath))
            {
                Directory.Delete(BackUpPath, true);
            }
            Directory.CreateDirectory(BackUpPath);

            try
            {
                File.Copy(Comm.MetaBasePath(), Path.Combine(BackUpPath, "MetaBase.xml"), true);

                if (chkHistory.Checked)
                {
                    DirectoryCopy(Environment.SystemDirectory + @"\inetsrv\History", Path.Combine(BackUpPath, "History"), "Metabase*.xml");
                }

                if (chkMetaBack.Checked)
                {
                    DirectoryCopy(Environment.SystemDirectory + @"\inetsrv\MetaBack", Path.Combine(BackUpPath, "MetaBack"), null);
                }

                if (chkACL.Checked)
                {
                    Dictionary <string, string> dict = new Dictionary <string, string>();
                    DataTable dt = Comm.GetAllWebInfo();
                    for (int i = 0; i < dt.Rows.Count; i++)
                    {
                        string _path = dt.Rows[i]["Path"].ToString();
                        if (!dict.ContainsKey(_path))
                        {
                            dict.Add(_path, "," + string.Join(",", NTFS.ACL.List(_path).ToArray()) + ",");
                        }
                    }

                    DataSet ds = new DataSet();

                    DataTable dtNew = new DataTable("CrazyIIS.ACL");
                    dtNew.Columns.Add("Path");
                    dtNew.Columns.Add("ACL");

                    foreach (var item in dict)
                    {
                        dtNew.Rows.Add(item.Key, item.Value);
                    }
                    ds.Tables.Add(dtNew);
                    ds.WriteXml(BackUpPath + "\\ACL.xml");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }



            MessageBox.Show("备份成功");
        }
예제 #4
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Stopwatch sp = new Stopwatch();

            sp.Start();

            //路径,用户名,密码
            WinNT.NetUser User   = new WinNT.NetUser();
            DataTable     dtUser = Comm.GetAllWebInfo();

            dtUser.Columns["AppPoolId"].ColumnName      = "U";
            dtUser.Columns["ServerBindings"].ColumnName = "P";
            Dictionary <string, string> AllUsers = new Dictionary <string, string>();

            for (int i = 0; i < dtUser.Rows.Count; i++)
            {
                string AnonymousUserName = txtUserNamePre.Text.Trim() + Regex.Replace(dtUser.Rows[i]["Web"].ToString(), @"\.|-", "_");
                string AnonymousUserPass = "";
                if (AnonymousUserName.Length > 20)
                {
                    AnonymousUserName = AnonymousUserName.Substring(0, 20);
                }
                if (AllUsers.ContainsKey(AnonymousUserName))
                {
                    AnonymousUserPass = AllUsers[AnonymousUserName];
                }
                else
                {
                    AnonymousUserPass = Comm.Random(Convert.ToInt32(txtPasswordNumber.Value));
                    AllUsers.Add(AnonymousUserName, AnonymousUserPass);
                }
                dtUser.Rows[i]["U"] = AnonymousUserName;
                dtUser.Rows[i]["P"] = AnonymousUserPass;
            }

            #region  除所有要删除的用户
            {
                backgroundWorker1.ReportProgress(25, "将要删除用户" + sp.ElapsedMilliseconds.ToString());
                List <String> _NowUsers = WinNT.User.List();
                foreach (string item in AllUsers.Keys)
                {
                    if (_NowUsers.Contains(item))
                    {
                        backgroundWorker1.ReportProgress(25, "正在删除用户:" + item);
                        User.UserDelete(item);
                    }
                }
                _NowUsers = null;
                backgroundWorker1.ReportProgress(28, "删除用户完成" + sp.ElapsedMilliseconds.ToString());
            }
            #endregion

            #region 创建所有要创建的用户
            {
                backgroundWorker1.ReportProgress(25, "将要创建用户" + sp.ElapsedMilliseconds.ToString());
                foreach (KeyValuePair <string, string> item in AllUsers)
                {
                    backgroundWorker1.ReportProgress(50, "正在创建匿名用户:" + item.Key);
                    User.UserAdd(item.Key, item.Value, null);
                }

                backgroundWorker1.ReportProgress(50, "创建匿名用户OK" + sp.ElapsedMilliseconds.ToString());
            }
            #endregion

            #region 匿名用户给网站
            {
                backgroundWorker1.ReportProgress(50, "将要 给网站添加匿名用户" + sp.ElapsedMilliseconds.ToString());

                IISConfig.Metabase metabase = new IISConfig.Metabase();
                metabase.OpenLocalMachine();

                IISConfig.IKey key = metabase.GetKeyFromPath("/LM/W3SVC");

                IISConfig.Record recordU = key.GetRecord(6020);
                IISConfig.Record recordP = key.GetRecord(6021);


                for (int i = 0; i < dtUser.Rows.Count; i++)
                {
                    key = metabase.GetKeyFromPath("/LM/W3SVC/" + dtUser.Rows[i]["Id"].ToString() + "/root");
                    //用户名存在时,设置密码
                    recordU.Data = dtUser.Rows[i]["U"].ToString();
                    recordP.Data = dtUser.Rows[i]["P"].ToString();
                    key.SetRecord(recordU);
                    key.SetRecord(recordP);
                }

                backgroundWorker1.ReportProgress(50, "给网站添加匿名用户完成" + sp.ElapsedMilliseconds.ToString());
            }
            #endregion

            #region 取网站路径及对应的用户名,如果路径存在,则加权限
            {
                backgroundWorker1.ReportProgress(50, "将要给目录加权限" + sp.ElapsedMilliseconds.ToString());

                for (int i = 0; i < dtUser.Rows.Count; i++)
                {
                    string NowPath = dtUser.Rows[i]["Path"].ToString();
                    if (Directory.Exists(NowPath))
                    {
                        backgroundWorker1.ReportProgress(50, "正在给目录 “" + NowPath + "” 加权限" + sp.ElapsedMilliseconds.ToString());
                        NTFS.ACL.Add(NowPath, dtUser.Rows[i]["U"].ToString(), NTFS.ACL.Roles.FullControl);
                        NTFS.ACL.DelErr(NowPath);
                    }
                }
                backgroundWorker1.ReportProgress(50, "给目录加权限完成" + sp.ElapsedMilliseconds.ToString());
            }
            #endregion

            sp.Stop();
            backgroundWorker1.ReportProgress(100, "操作完成 共用时:" + sp.ElapsedMilliseconds / 1000 + "s");
        }
예제 #5
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            try
            {
                List <string> listHeader = new List <string>();
                string        _filename  = Comm.GetAttributesByPath("/mxh:configuration/mxh:MBProperty/mxh:IIsWebServer[@Location ='/LM/W3SVC/" + Id + "']", "LogFileDirectory");
                if (string.IsNullOrEmpty(_filename))
                {
                    _filename = Comm.GetIIsWebServiceAttributesByPath("LogFileDirectory");
                }
                _filename = _filename + "\\W3SVC" + Id + "\\" + LogFile;

                FileStream   fs     = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                StreamReader reader = new StreamReader(fs, System.Text.Encoding.Default);

                int fileIndex = 0;

                while (reader.Peek() > -1)
                {
                    string line = reader.ReadLine();
                    if (string.IsNullOrEmpty(line))
                    {
                        continue;
                    }

                    if (IsLogHeader(line))
                    {
                        if (line.StartsWith("#Fields:"))
                        {
                            string   temp   = line.Substring(9).Trim();
                            string[] header = temp.Split(new char[] { ' ' });
                            listHeader.AddRange(header);
                            fileIndex = listHeader.IndexOf("cs-uri-stem");
                        }
                    }
                    else
                    {
                        if (
                            !listHeader.Contains("date") ||
                            !listHeader.Contains("time") ||
                            !listHeader.Contains("cs-uri-stem") ||
                            !listHeader.Contains("time-taken") ||
                            !listHeader.Contains("cs-host")

                            )
                        {
                            continue;
                        }

                        string[] _fieldsItem = line.Split(new char[] { ' ' });

                        if (_fieldsItem[fileIndex].IndexOfAny(Path.GetInvalidPathChars()) == -1 && Path.HasExtension(_fieldsItem[fileIndex]))
                        {
                            string ext = Path.GetExtension(_fieldsItem[fileIndex]).Substring(1);
                            if ("asp|asa|aspx|ascx|php|php2|php3|php4|php5".IndexOf(ext) > -1)
                            {
                                if (Convert.ToDecimal(_fieldsItem[listHeader.IndexOf("time-taken")]) > numericUpDown1.Value)
                                {
                                    dtNow.Rows.Add(
                                        TimeZone.CurrentTimeZone.ToLocalTime(Convert.ToDateTime(_fieldsItem[listHeader.IndexOf("date")] + " " + _fieldsItem[listHeader.IndexOf("time")])),
                                        "http://" + _fieldsItem[listHeader.IndexOf("cs-host")] + _fieldsItem[listHeader.IndexOf("cs-uri-stem")],
                                        _fieldsItem[listHeader.IndexOf("time-taken")]
                                        );
                                }
                            }
                        }
                    }
                }
                fs.Close();
                reader.Close();
            }
            catch (Exception ex)
            {
                dtNow.Rows.Add(null, null, null, ex.Message);
            }
        }
예제 #6
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            if (!File.Exists(Comm.MetaBasePath()))
            {
                MessageBox.Show("请确认您已经安装IIS 6.0");
                return;
            }

            Stopwatch sp = new Stopwatch();

            sp.Start();

            backgroundWorker1.ReportProgress(5, "正在停止IIS");
            IIS.Stop();


            string MetaBase                 = File.ReadAllText(Comm.MetaBasePath());
            string MetaBase_BackUp          = File.ReadAllText(txtRestore.Text);
            string Defult_AnonymousUserName = Comm.GetDefaultAnonymousUserName();


            WinNT.NetUser User = new WinNT.NetUser();
            Dictionary <string, string> AllUsers = new Dictionary <string, string>();
            DataTable PathUser = new DataTable();

            PathUser.Columns.Add("Path");
            PathUser.Columns.Add("User");


            #region MetaBase_BackUp 前期处理
            {
                //把“机器名\\用户名”处理成“用户名”
                MetaBase_BackUp = Regex.Replace(MetaBase_BackUp, @"AnonymousUserName=""[^""]+\\([^""]+?)""", @"AnonymousUserName=""$1""");
                //有些机器会生成“UNCPassword”自定义结点,影响工作,删除
                MetaBase_BackUp = Regex.Replace(MetaBase_BackUp, @"<Custom[^<>]+?UNCPassword[\s\S]+?/>", "", RegexOptions.Multiline | RegexOptions.IgnoreCase);
                MetaBase_BackUp = Regex.Replace(MetaBase_BackUp, @"[a-zA-Z]:\\Windows", Environment.GetEnvironmentVariable("windir"), RegexOptions.IgnoreCase);
            }
            #endregion

            #region 加工 MetaBase_BackUp 一些安全属性为当前属性
            {
                XmlDocument doc_Now = new XmlDocument();
                doc_Now.LoadXml(MetaBase);
                XmlNamespaceManager xnm = new XmlNamespaceManager(doc_Now.NameTable);
                xnm.AddNamespace("mxh", "urn:microsoft-catalog:XML_Metabase_V64_0");

                XmlDocument doc_Bak = new XmlDocument();
                doc_Bak.LoadXml(MetaBase_BackUp);

                //string[] Nodes = "IIsWebService|IIsFilters|IIsApplicationPools|IIsLogModules|IIsFtpService|IIsNNTPService|IIsSMTPService|IIsIMAPService|IIsPOP3Service|IIsMiMeMap".Split('|');
                string[] IIS_Nodes  = "IIsWebService|IIsFilters|IIsApplicationPools|IIsLogModules|IIsFtpService".Split('|');
                string[] IIS_Fileds = "AnonymousUserName|AnonymousUserPass|LogOdbcPassword|LogOdbcPassword|WAMUserName|WAMUserPass|AdminACL".Split('|');

                foreach (string item in IIS_Nodes)
                {
                    string  xpath   = "/mxh:configuration/mxh:MBProperty/mxh:" + item;
                    XmlNode IIS_Now = doc_Now.SelectSingleNode(xpath, xnm);
                    XmlNode IIS_Bak = doc_Bak.SelectSingleNode(xpath, xnm);

                    //如果一个没有这个结点就直接进入下一个结点
                    if (IIS_Now == null || IIS_Bak == null)
                    {
                        continue;
                    }

                    //各属性同步
                    foreach (string item2 in IIS_Fileds)
                    {
                        if (IIS_Now.Attributes[item2] != null && IIS_Bak.Attributes[item2] == null)
                        {
                            ((XmlElement)IIS_Bak).RemoveAttribute(item2);
                        }

                        if (IIS_Now.Attributes[item2] != null && IIS_Bak.Attributes[item2] != null)
                        {
                            IIS_Bak.Attributes[item2].Value = IIS_Now.Attributes[item2].Value;
                        }
                    }
                }

                MetaBase_BackUp = doc_Bak.OuterXml;
            }
            #endregion

            #region IIsMimeMap
            {
                backgroundWorker1.ReportProgress(10, "还原网站配置");
                string temp = Regex.Match(MetaBase_BackUp, "<IIsMimeMap[^<>]+?>").Groups[0].Value;
                MetaBase = Regex.Replace(MetaBase, "<IIsMimeMap[^<>]+?>", temp);
            }
            #endregion

            #region IIsWebService
            {
                backgroundWorker1.ReportProgress(10, "还原网站配置");
                string temp = Regex.Match(MetaBase_BackUp, "<IIsWebService[^<>]+?>").Groups[0].Value;
                MetaBase = Regex.Replace(MetaBase, "<IIsWebService[^<>]+?>", temp);
            }
            #endregion

            #region IIsWebServer
            {
                backgroundWorker1.ReportProgress(15, "还原网站" + sp.ElapsedMilliseconds.ToString());

                string temp = "";
                if (Comm.IsReg())
                {
                    temp = Regex.Match(MetaBase_BackUp, "</IIsWebService>([\\s\\S]+)<IIsApplicationPools").Groups[1].Value;
                }
                else
                {
                    ////////////MatchCollection WebsitesMatches = Regex.Matches(MetaBase_BackUp, "<IIsWebServer\\s+Location=\"/LM/W3SVC/\\d+\"[\\s\\S]+?</IIsWebVirtualDir>",RegexOptions.IgnoreCase);
                    ////////////int TestI = 0;
                    ////////////foreach (Match item in WebsitesMatches)
                    ////////////{
                    ////////////    temp += item.Value;
                    ////////////    TestI++;
                    ////////////    if (TestI == 25)
                    ////////////    {
                    ////////////        break;
                    ////////////    }
                    ////////////}

                    List <string>   sss             = new List <string>();
                    MatchCollection WebsitesMatches = Regex.Matches(MetaBase_BackUp, "(<IIsWebServer\\s+Location=\"/LM/W3SVC/\\d+\"[\\s\\S]+)<IIsApplicationPools", RegexOptions.IgnoreCase);

                    if (WebsitesMatches.Count > 0)
                    {
                        sss.AddRange(WebsitesMatches[0].Groups[1].Value.Replace("<IIsWebServer", "柳永法<IIsWebServer").Split(new string[] { "柳永法" }, StringSplitOptions.RemoveEmptyEntries));
                    }

                    int TestI = 0;
                    foreach (string item in sss)
                    {
                        temp += item;
                        TestI++;
                        if (TestI == 25)
                        {
                            break;
                        }
                    }
                }

                temp     = Regex.Replace(temp, @"(AnonymousUserPass|UNCPassword|AdminACL)\s*=\s*"".+?""", "");
                MetaBase = Regex.Replace(MetaBase, "</IIsWebService>[\\s\\S]+<IIsApplicationPools", "</IIsWebService>" + temp + "<IIsApplicationPools");
            }
            #endregion

            #region IIsApplicationPools
            {
                backgroundWorker1.ReportProgress(20, "还原应用程序池配置" + sp.ElapsedMilliseconds.ToString());
                //"<IIsApplicationPools[\\s\\S]+</IIsApplicationPools>"
                string temp = Regex.Match(MetaBase_BackUp, "<IIsApplicationPools[^<>]+?>").Groups[0].Value;
                //可能会有,所有替换
                temp     = Regex.Replace(temp, @"(WAMUserName|WAMUserPass)\s*=\s*"".+?""", "");
                MetaBase = Regex.Replace(MetaBase, "<IIsApplicationPools[^<>]+?>", temp);
            }
            #endregion

            #region ApplicationPool
            {
                backgroundWorker1.ReportProgress(25, "还原应用程序池" + sp.ElapsedMilliseconds.ToString());
                string temp = Regex.Match(MetaBase_BackUp, "</IIsApplicationPools>([\\s\\S]+)</IIsApplicationPool>").Groups[1].Value;
                temp     = Regex.Replace(temp, @"(WAMUserName|WAMUserPass)\s*=\s*"".+?""", "");
                MetaBase = Regex.Replace(MetaBase, "</IIsApplicationPools>[\\s\\S]+</IIsApplicationPool>", "</IIsApplicationPools>" + temp + "</IIsApplicationPool>");
            }
            #endregion


            #region IIsLogModules
            {
                backgroundWorker1.ReportProgress(15, "还原LogModules" + sp.ElapsedMilliseconds.ToString());
                string temp = "";
                temp     = Regex.Match(MetaBase_BackUp, "<IIsLogModules>([\\s\\S]+)</IIsCustomLogModule>").Groups[1].Value;
                MetaBase = Regex.Replace(MetaBase, "<IIsLogModules>([\\s\\S]+)</IIsCustomLogModule>", temp);
            }
            #endregion

            #region IIsFilters
            {
                backgroundWorker1.ReportProgress(15, "还原LogModules" + sp.ElapsedMilliseconds.ToString());
                string temp = "";
                temp     = Regex.Match(MetaBase_BackUp, "<IIsFilters>([\\s\\S]+)</IIsCompressionSchemes>").Groups[1].Value;
                MetaBase = Regex.Replace(MetaBase, "<IIsFilters>([\\s\\S]+)</IIsCompressionSchemes>", temp);
            }
            #endregion

            if (chkFtp.Checked && MetaBase.Contains("<IIsFtpService"))
            {
                #region IIsFtpService
                {
                    backgroundWorker1.ReportProgress(10, "还原网站配置");
                    string temp = Regex.Match(MetaBase_BackUp, "<IIsFtpService[^<>]+?>").Groups[0].Value;
                    MetaBase = Regex.Replace(MetaBase, "<IIsFtpService[^<>]+?>", temp);
                }
                #endregion

                #region IIsFtpService
                {
                    backgroundWorker1.ReportProgress(15, "还原网站" + sp.ElapsedMilliseconds.ToString());
                    string temp = "";
                    temp     = Regex.Match(MetaBase_BackUp, "</IIsFtpService>([\\s\\S]+)<IIsFtpInfo").Groups[1].Value;
                    temp     = Regex.Replace(temp, @"(AnonymousUserPass|UNCPassword|AdminACL)\s*=\s*"".+?""", "");
                    MetaBase = Regex.Replace(MetaBase, "</IIsFtpService>([\\s\\S]+)<IIsFtpInfo", "</IIsFtpService>" + temp + "<IIsFtpInfo");
                }
                #endregion
            }



            File.WriteAllText(Comm.MetaBasePath(), MetaBase);

            backgroundWorker1.ReportProgress(25, "IIS还原完成,将要创建匿名用户,时间较长" + sp.ElapsedMilliseconds.ToString());

            #region 取得所有匿名用户并重新给他们密码
            {
                MatchCollection _AnonymousUserName = Regex.Matches(MetaBase, @"AnonymousUserName=""(.+?)""");
                for (int i = 0; i < _AnonymousUserName.Count; i++)
                {
                    Match item = _AnonymousUserName[i];
                    if (!AllUsers.ContainsKey(item.Groups[1].Value))
                    {
                        AllUsers.Add(item.Groups[1].Value, Comm.Random(i, 10));
                    }
                }
            }
            #endregion

            #region  除所有要删除的用户
            {
                backgroundWorker1.ReportProgress(25, "将要删除用户" + sp.ElapsedMilliseconds.ToString());
                List <String> _NowUsers = WinNT.User.List();
                foreach (string item in AllUsers.Keys)
                {
                    if (_NowUsers.Contains(item))
                    {
                        backgroundWorker1.ReportProgress(25, "正在删除用户:" + item);
                        User.UserDelete(item);
                    }
                }
                _NowUsers = null;
                backgroundWorker1.ReportProgress(28, "删除用户完成" + sp.ElapsedMilliseconds.ToString());
            }
            #endregion

            #region 创建所有要创建的用户
            {
                backgroundWorker1.ReportProgress(25, "将要创建用户" + sp.ElapsedMilliseconds.ToString());
                foreach (KeyValuePair <string, string> item in AllUsers)
                {
                    backgroundWorker1.ReportProgress(50, "正在创建匿名用户:" + item.Key);
                    User.UserAdd(item.Key, item.Value, null);
                }

                backgroundWorker1.ReportProgress(50, "创建匿名用户OK" + sp.ElapsedMilliseconds.ToString());
            }
            #endregion

            #region 匿名用户给网站
            {
                backgroundWorker1.ReportProgress(50, "将要 给网站添加匿名用户" + sp.ElapsedMilliseconds.ToString());

                IISConfig.Metabase metabase = new IISConfig.Metabase();
                metabase.OpenLocalMachine();

                IISConfig.IKey   key    = metabase.GetKeyFromPath("/LM/W3SVC");
                IISConfig.Record record = key.GetRecord(6021);

                //更新"/LM/W3SVC"的默认用户密码
                record.Data = AllUsers[key.GetRecord(6020).Data.ToString()];
                key.SetRecord(record);



                MatchCollection matchs = Regex.Matches(MetaBase, @"Location\s*=\s*""(/LM/W3SVC/\d+/root.*?)""", RegexOptions.IgnoreCase);
                foreach (Match item in matchs)
                {
                    key = metabase.GetKeyFromPath(item.Groups[1].Value);
                    if (key.GetRecord(6020) != null)
                    {
                        //用户名存在时,设置密码
                        record.Data = AllUsers[key.GetRecord(6020).Data.ToString()];
                        key.SetRecord(record);
                        PathUser.Rows.Add(key.GetRecord(3001).Data.ToString(), key.GetRecord(6020).Data.ToString());
                    }
                    else
                    {
                        //用户名不存在时,删除密码
                        if (key.GetRecord(6021) != null)
                        {
                            key.DeleteRecord(6021);
                        }

                        PathUser.Rows.Add(key.GetRecord(3001).Data.ToString(), Defult_AnonymousUserName);
                    }
                }
                metabase.Close();
                backgroundWorker1.ReportProgress(50, "给网站添加匿名用户完成" + sp.ElapsedMilliseconds.ToString());
            }
            #endregion

            #region 取网站路径及对应的用户名,如果路径存在,则加权限
            {
                backgroundWorker1.ReportProgress(50, "将要给目录加权限" + sp.ElapsedMilliseconds.ToString());

                for (int i = 0; i < PathUser.Rows.Count; i++)
                {
                    string NowPath = PathUser.Rows[i][0].ToString();
                    if (chkDir.Checked && !Directory.Exists(NowPath))
                    {
                        Directory.CreateDirectory(NowPath);
                        File.WriteAllText(NowPath + "\\CrazyIIS.html", "hello html");
                        File.WriteAllText(NowPath + "\\CrazyIIS.asp", "<%=1+1%> ASP Test OK");
                        File.WriteAllText(NowPath + "\\CrazyIIS.aspx", "<%=1+1%> ASPX Test OK");
                    }

                    if (Directory.Exists(NowPath))
                    {
                        backgroundWorker1.ReportProgress(50, "正在给目录 “" + NowPath + "” 加权限" + sp.ElapsedMilliseconds.ToString());
                        NTFS.ACL.Add(NowPath, PathUser.Rows[i][1].ToString(), NTFS.ACL.Roles.FullControl);
                        NTFS.ACL.DelErr(NowPath);
                    }
                }
                backgroundWorker1.ReportProgress(50, "给目录加权限完成" + sp.ElapsedMilliseconds.ToString());
            }
            #endregion


            #region 是否写入 hosts
            if (chkHosts.Checked)
            {
                backgroundWorker1.ReportProgress(90, "正在写入hosts" + sp.ElapsedMilliseconds.ToString());
                MatchCollection matchs = Regex.Matches(MetaBase, "ServerComment=\"(.+?)\"", RegexOptions.IgnoreCase);
                string          Hosts  = "";
                foreach (Match item in matchs)
                {
                    Hosts += ",127.0.0.1," + item.Groups[1].Value;
                }
                Comm.Write2hosts(Hosts.Substring(1).Split(','), true);
            }
            #endregion


            backgroundWorker1.ReportProgress(90, "正在重启IIS" + sp.ElapsedMilliseconds.ToString());

            IIS.Start();

            sp.Stop();
            backgroundWorker1.ReportProgress(100, "操作完成 共用时:" + sp.ElapsedMilliseconds / 1000 + "s");
        }
예제 #7
0
 private void FrmMonitor_Load(object sender, EventArgs e)
 {
     Comm.DataGridViewSet(dataGridView1);
     FirstFill();
 }
예제 #8
0
        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            Dictionary <string, string> days = new Dictionary <string, string>();

            for (int i = 0; i < (dtp2.Value.Date - dtp1.Value.Date).Days + 1; i++)
            {
                days.Add(dtp1.Value.AddDays(i).ToString("yyyy-MM-dd"), dtp1.Value.AddDays(i).ToString("exyyMMdd") + ".log");
            }

            int    NowIndex    = -1;
            string NowWeb_Name = new List <string>(NowWeb.Keys)[0];
            string NowWeb_Id   = NowWeb[NowWeb_Name];

            foreach (var item in days)
            {
                NowIndex++;

                LogInfo _loginfo = new LogInfo();
                _loginfo.OptTime = item.Key;
                _loginfo.Web     = NowWeb_Name;

                try
                {
                    List <string> listHeader = new List <string>();
                    string        _filename  = Comm.GetAttributesByPath("/mxh:configuration/mxh:MBProperty/mxh:IIsWebServer[@Location ='/LM/W3SVC/" + NowWeb_Id + "']", "LogFileDirectory");
                    if (string.IsNullOrEmpty(_filename))
                    {
                        _filename = Comm.GetIIsWebServiceAttributesByPath("LogFileDirectory");
                    }
                    _filename = _filename + "\\W3SVC" + NowWeb_Id + "\\" + item.Value;

                    FileStream   fs     = new FileStream(_filename, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    StreamReader reader = new StreamReader(fs, System.Text.Encoding.Default);

                    int fileIndex = 0;

                    while (reader.Peek() > -1)
                    {
                        string line = reader.ReadLine();
                        if (string.IsNullOrEmpty(line))
                        {
                            continue;
                        }

                        if (IsLogHeader(line))
                        {
                            if (line.StartsWith("#Fields:"))
                            {
                                string   temp   = line.Substring(9).Trim();
                                string[] header = temp.Split(new char[] { ' ' });
                                listHeader.AddRange(header);
                                fileIndex = listHeader.IndexOf("cs-uri-stem");
                            }
                        }
                        else
                        {
                            if (!listHeader.Contains("cs-uri-stem") || !listHeader.Contains("sc-bytes") || !listHeader.Contains("cs-bytes") || !listHeader.Contains("sc-status"))
                            {
                                continue;
                            }

                            string[] _fieldsItem = line.Split(new char[] { ' ' });

                            double _sc_bytes = Convert.ToDouble(_fieldsItem[listHeader.IndexOf("sc-bytes")]);
                            double _cs_bytes = Convert.ToDouble(_fieldsItem[listHeader.IndexOf("cs-bytes")]);
                            if (_fieldsItem[fileIndex].IndexOfAny(Path.GetInvalidPathChars()) == -1 && Path.HasExtension(_fieldsItem[fileIndex]))
                            {
                                string ext = Path.GetExtension(_fieldsItem[fileIndex]).Substring(1);
                                if (Ext_html.IndexOf(ext) > -1)
                                {
                                    _loginfo.HTML += _sc_bytes;
                                }
                                else if (Ext_Dynamic.IndexOf(ext) > -1)
                                {
                                    _loginfo.ASP += _sc_bytes;
                                }
                                else if (Ext_Compress.IndexOf(ext) > -1)
                                {
                                    _loginfo.RAR += _sc_bytes;
                                }
                                else if (Ext_Picture.IndexOf(ext) > -1)
                                {
                                    _loginfo.Pic += _sc_bytes;
                                }
                                else if (Ext_Music.IndexOf(ext) > -1)
                                {
                                    _loginfo.Music += _sc_bytes;
                                }
                                else if (Ext_Movie.IndexOf(ext) > -1)
                                {
                                    _loginfo.Movie += _sc_bytes;
                                }
                                if (_fieldsItem[listHeader.IndexOf("sc-status")] == "500")
                                {
                                    _loginfo.ASP500 = _loginfo.ASP500 + 1;
                                }
                                _loginfo.Down += _sc_bytes;
                                _loginfo.Up   += _cs_bytes;
                            }
                        }
                    }
                    fs.Close();
                    reader.Close();


                    if (_loginfo.Down + _loginfo.Up == 0)
                    {
                        _loginfo.Remark = "您的IIS日志不信息不足,请先设置日志记录格式!";
                    }
                    backgroundWorker1.ReportProgress(NowIndex * 100 / days.Count, _loginfo);
                }
                catch (Exception ex)
                {
                    _loginfo.Remark = "错误:" + ex.Message;
                    backgroundWorker1.ReportProgress(NowIndex * 100 / days.Count, _loginfo);
                }
            }
        }