有关域服务器免登录问题以及获取域服务器下所有登录账号【深海原创】

原文地址:http://blog.csdn.net/lfywy/archive/2008/07/16/2658623.aspx

前段日子在CSDN上求助:http://topic.csdn.net/u/20080702/21/fc3826ba-2296-41f6-8049-3d0fbe5710b8.html

最后还是自己研究解决了问题:

首先,在B/S上登录首先判断是否在域中:

<script language="javascript" type="text/javascript">
var Is=&apos;<%=Is%>&apos;;
var IsTo=&apos;<%=IsTo%>&apos;;
 //获取浏览器窗口宽
function getViewportInfoWidth()
{
    var w = (window.innerWidth) ? window.innerWidth : (document.documentElement && document.documentElement.clientWidth) ? document.documentElement.clientWidth : document.body.offsetWidth;

    return w;
}
//获取浏览器窗口高
function getViewportInfoHeight()
{

    var h = (window.innerHeight) ? window.innerHeight : (document.documentElement && document.documentElement.clientHeight) ? document.documentElement.clientHeight : document.body.offsetHeight;
    return h;
}
 
document.getElementById("login").width=getViewportInfoWidth();
document.getElementById("login").height=getViewportInfoHeight();
if(Is=="1")
{
try{
  var   WshNetwork   =   new   ActiveXObject("WScript.Network");
  window.location="Login.aspx?lug="+WshNetwork.UserName+"&don="+WshNetwork.UserDomain;//拿到域名 
  }catch(e){alert("请您把本站添加为可信任的站点或ActiveX控件和插件设为启用!然后重新登录系统!错误:"+e.toString());}
}
if(IsTo=="1")
{
    window.location="LoginIndex.aspx";
}
</script>

不过要首先判断是否在某个网段内,CS代码:

/// <summary>
        /// 判断是否为DomainIP,Webconfig里配置的网段
        /// </summary>
        /// <returns></returns>
        private bool IsLan()
        {
            num = Convert.ToInt32(DomainNum);
            LoHostIP = HttpContext.Current.Request.UserHostAddress;
            IPSectCon = DomainIP.Split(new char[1] { &apos;.&apos; });
            IPSectLoc = LoHostIP.Split(new char[1] { &apos;.&apos; });
            if (num == 0)
            {
                IPCon = "127";//不需要通过域服务器IP来选择的情况
                IPLoc = "";
            }
            for (int i = 0; i < num; i++)
            {
                if (i == 0)
                {
                    IPCon += IPSectCon[i];
                    IPLoc += IPSectLoc[i];
                }
                else
                {
                    IPCon += "." + IPSectCon[i];
                    IPLoc += "." + IPSectLoc[i];
                }
            }
            IPCon = IPSectCon[0];
            IPLoc = IPSectLoc[0];
            if (IPCon.Equals(IPLoc) || IPCon.Equals("127") || IPCon.Equals("127.0") || IPCon.Equals("127.0.0") || IPCon.Equals("127.0.0.1"))
            {
                return true;
            }
            return false;
        }

这样解决了,免登录问题,不过免登录首先还得需和数据里的用户表挂钩,此时就做了一个C/S架构的服务器,把在域里的所有登录账号用户先录入到数据库中,这样做以上步骤就顺理成章了!如下服务器截图:

做好的C/S之后打包,安装后如下图:

界面信息:

 


上面显示了CN=Users的账号都是域用户登录账号,不过不同的域可能这里的名字不一样,我们到用户那里部署时却是semd_user,当然可以在config里设置!

打开后右下方显示如下托盘:

 


桌面添加为以下:

 


程序里添加如下:

 


从上面又学了一招打包,不过卸载也是很简单,打包生成好后有一个叫.msi文件,调用此文件即可修复程序或卸载程序!到此解决问题!

 域服务器的关键代码如下:

#region 获取设定的域服务器信息
        /// <summary>
        /// 获取设定的域服务器信息
        /// </summary>
        protected void SetLogonInformation()
        {
            UserType = (ConfigurationSettings.AppSettings["UserType"] == "" ? null : ConfigurationSettings.AppSettings["UserType"]);
            UserServer = (ConfigurationSettings.AppSettings["UserServer"] == "" ? null : ConfigurationSettings.AppSettings["UserServer"]);
            RoleId = (ConfigurationSettings.AppSettings["RoleId"] == "" ? null : ConfigurationSettings.AppSettings["RoleId"]);
            SQLPwd = (ConfigurationSettings.AppSettings["SQLPwd"] == "" ? null : ConfigurationSettings.AppSettings["SQLPwd"]);
            DUserPwd = (ConfigurationSettings.AppSettings["DUserPwd"] == "" ? null : ConfigurationSettings.AppSettings["DUserPwd"]);
            username = (ConfigurationSettings.AppSettings["DomainUN"] == "" ? null : ConfigurationSettings.AppSettings["DomainUN"]);
            password = (ConfigurationSettings.AppSettings["DomainPW"] == "" ? null : ConfigurationSettings.AppSettings["DomainPW"]);
            hostname = (ConfigurationSettings.AppSettings["DomainIP"] == "" ? null : ConfigurationSettings.AppSettings["DomainIP"]);
            if (hostname != "") hostname += "/";
        }

        /// <summary>
        /// 获取设定的域服务器信息SetNaming
        /// </summary>
        protected void SetNamingContext()
        {
            using (DirectoryEntry de = new DirectoryEntry())
            {
                string path = "LDAP://" + hostname + "rootDSE";
                de.Username = username;
                de.Password = password;
                de.Path = path;

                schemaNamingContext = de.Properties["schemaNamingContext"][0].ToString();
                defaultNamingContext = de.Properties["defaultNamingContext"][0].ToString();
            }
        }

        /// <summary>
        /// 设置参数
        /// </summary>
        /// <returns></returns>
        protected string[] GetProperties()
        {
            string[] properties = new string[1];
            //int i = 0;
            //int bs = 0;
            //for (int j = 0; j < listBoxProperties.SelectedItems.Count; j++)
            //{
            //    if (listBoxProperties.Items[j].ToString() == "userPassword")
            //    {
            //        bs = j;
            //    }
            //}
            ////new listBoxProperties.SelectedItems[bs];
            //foreach (string s in listBoxProperties.SelectedItems)
            //{
            //    properties[i++] = s;
            //}
            properties[0] = "userPassword";
            return properties;
        }

        protected string[] GetSchemaProperties(string schemaNamingContext, string objectType)
        {
            string[] data;
            using (DirectoryEntry de = new DirectoryEntry())
            {
                de.Username = username;
                de.Password = password;
                de.Path = "LDAP://" + hostname + "CN=" + objectType + "," + schemaNamingContext;
                DS.PropertyCollection properties = de.Properties;
                DS.PropertyValueCollection values = properties["systemMayContain"];
                data = new String[values.Count];
                values.CopyTo(data, 0);
            }
            return data;
        }

        protected void SetUserProperties(string schemaNamingContext)
        {
            StringCollection properties = new StringCollection();
            string[] data = GetSchemaProperties(schemaNamingContext, "User");
            properties.AddRange(GetSchemaProperties(schemaNamingContext, "Organizational-Person"));
            properties.AddRange(GetSchemaProperties(schemaNamingContext, "Person"));
            properties.AddRange(GetSchemaProperties(schemaNamingContext, "Top"));
        }
        #endregion

        #region 线程数据提示语
        private void ThreadProcUnsafe()
        {
            this.txtbox.Text = "This text was set unsafely.";
        }

        private void ThreadProcSafe()
        {
            this.SetText("This text was set safely.");
        }
        #endregion

        #region 利用委托方法把内容显示在textbox上
        private void SetText(string text)
        {
            k = 1;
            p = 1;
            try
            {
                if (this.txtbox.InvokeRequired)
                {
                    SetTextCallback d = new SetTextCallback(SetText);
                    this.Invoke(d, new object[] { text });
                }
                else
                {
                    this.txtbox.Text = text;
                    ustr=text.Split(new char[1] { &apos;|&apos; });
                    userstr = this.txtbox.Text;
                    this.txtbox.Text = userstr;
                    userstr = "";
                    for (int i = 0; i < ustr.Length-1; i++)
                    {
                        ustrr = ustr[i].Split(new char[1] { &apos;,&apos; });
                        uname = ustrr[0].Split(new char[1] { &apos;=&apos; });
                        utype = ustrr[1].Split(new char[1] { &apos;=&apos; });
                        utype2 = ustrr[2].Split(new char[1] { &apos;=&apos; });
                        if ((utype[1] == UserType) || (utype2[1] == UserType))
                        {
                            AccessData(uname[1]);
                            if (i == 0)
                            {
                                userstr += Convert.ToString(p++) + "、" + uname[1] + "\r\n";
                            }
                            else
                            {
                                userstr += Convert.ToString(p++) + "、" + uname[1] + "\r\n";
                            }
                        }
                    }
                    if (AccessUN == "")
                    {
                        AccessUN = "☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆暂时没有新添加的域登录账号☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆☆";
                    }
                    this.txtbox.Text = "服务器启动成功!\r\n****************************************************************************************************\r\n获取域下所有入库账号如下列表:\r\n" + AccessUN + "\r\n获取域下所有登录帐号如下列表:\r\n" + userstr + "\r\n****************************************************************************************************\r\n服务器获取该域所有登录用户成功!\r\n****************************************************************************************************\r\n域服务器参考信息如下:\r\n" + this.txtbox.Text;
                    this.txtbox.Text += "\r\nEND***************************************************************************************************";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请核对你的各种配置数据!错误:" + ex.Message);
                t.Close();
                Application.Exit();//退出应用程序
            }
        }
        #endregion

        #region 读取域下面的所有登录帐号并入程序WEB下~/App_Data/Sys.mdb库中
        public void AccessData(string username)
        {
            int userid;
            int sid;
            int SID;
            AccessUN = "";
            try
            {
                Name = username.Trim().Replace("&apos;", "‘");
                DataTable dt = (new sqlconn()).DataTable("select SID,USERNAME,USERLOGINNAME,COMID,TEL,EMAIL,USERID,ISUSING from UserInfo where USERLOGINNAME=&apos;" + Name + "&apos;");
                if (dt.Rows.Count <= 0)
                {
                    AccessUN += Convert.ToString(k++) + "、" + Name + "\r\n";
                    SID = (new sqlconn()).Max("select Max(SID) from USERINFO") + 1;
                    sid = (new sqlconn()).Max("select Max(SID) from USER2ROLE") + 1;
                    userid = (new sqlconn()).Max("SELECT max(USERID) FROM USERINFO") + 1;
                    //如果userid在USER2ROLE当中存在一个,则先删除此行
                    string strsql1 = "delete from USER2ROLE where USERID=" + userid;
                    string strsql2 = "insert into USERINFO (SID,USERID,USERNAME,USERLOGINNAME,USERPWD,COMID,TEL,EMAIL,ADDR)values(&apos;" + SID + "&apos;,&apos;" + userid + "&apos;,&apos;" + Name + "&apos;,&apos;" + Name + "&apos;,&apos;" + DUserPwd + "&apos;,&apos;0&apos;,&apos;&apos;,&apos;&apos;,&apos;&apos;)";
                    string strsql3 = "insert into USER2ROLE (SID,USERID,ROLEID)values(&apos;" + sid + "&apos;,&apos;" + userid + "&apos;,&apos;" + Convert.ToInt32(RoleId) + "&apos;)";
                    (new sqlconn()).ExecuteSql(strsql1);
                    (new sqlconn()).ExecuteSql(strsql2);
                    (new sqlconn()).ExecuteSql(strsql3);
                    DataTable dt2 = (new SqlDataAccess(UserServer)).RunSqlDT("select SID,USERNAME,USERLOGINNAME,COMID,TEL,EMAIL,USERID,ISUSING from UserInfo where USERLOGINNAME=&apos;" + Name + "&apos;");
                    if (dt2.Rows.Count <= 0)
                    {
                        string strsql2005 = "insert into USERINFO (SID,USERID,USERNAME,USERLOGINNAME,USERPWD,COMID,TEL,EMAIL,ADDR)values(&apos;" + SID + "&apos;,&apos;" + userid + "&apos;,&apos;" + Name + "&apos;,&apos;" + Name + "&apos;,&apos;" + SQLPwd + "&apos;,&apos;0&apos;,&apos;&apos;,&apos;&apos;,&apos;&apos;)";
                        (new SqlDataAccess(UserServer)).DataCom(strsql2005);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请核对你的config连接数据配置数据或改Sys.mdb为可写!或同步到sql2005表里时候出错,请核对各个连接字符串和配置是否正确!错误: " + ex.Message);
            }
        }
        #endregion

        #region 读取域信息
        public void ReadData(object source, System.Timers.ElapsedEventArgs e)
        {
            try
            {
                SetLogonInformation();
                SetNamingContext();

                SetUserProperties(schemaNamingContext);
                using (DirectoryEntry root = new DirectoryEntry())
                {
                    root.Username = username;
                    root.Password = password;
                    root.Path = "LDAP://" + hostname + defaultNamingContext;

                    using (DirectorySearcher searcher = new DirectorySearcher())
                    {
                        searcher.SearchRoot = root;
                        searcher.SearchScope = SearchScope.Subtree;
                        searcher.Filter = "(objectClass=user)";
                        searcher.PropertiesToLoad.AddRange(GetProperties());

                        SearchResultCollection results = searcher.FindAll();
                        StringBuilder summary = new StringBuilder();
                        foreach (SearchResult result in results)
                        {
                            foreach (string propName in result.Properties.PropertyNames)
                            {
                                foreach (string s in result.Properties[propName])
                                {
                                    summary.Append(" " + propName + ": " + s);
                                }
                            }
                            summary.Append("\r\n" + "|");
                        }
                        SetText(summary.ToString());//最后在屏幕上显示信息
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("请核对你的域服务器地址、账号、密码等配置数据!错误: " + ex.Message);
            }
        }
        #endregion

        #region 服务程序入口
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.Run(new GetDomainLUN());
        }
        #endregion

        #region 服务启动,服务停止,服务退出
        private void btnStart_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = false;
            btnCancel.Enabled = true;
            //t.Enabled = true;
            t.Start();
            this.lblxszt.Text = "运行中";
            this.lblxszt.ForeColor = System.Drawing.Color.Green;
        }

        private void btnGet_Click(object sender, EventArgs e)
        {
            btnStart.Enabled = true;
            btnCancel.Enabled = false;
            //t.Enabled = false;
            t.Stop();
            this.lblxszt.Text = "已停止";
            this.lblxszt.ForeColor = System.Drawing.Color.Red;
            t.Close();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            t.Close();
            Application.Exit();//退出应用程序 
        }
        #endregion

        #region 点击右下角图标应用程序显示与隐藏
        private void notifyIcon1_Click(object sender, EventArgs e)
        {
            if (con % 2 == 0)
            {
                this.Visible = false;
            }
            else
            {
                this.Visible = true;
            }
            con++;
        }
        #endregion

当然,域服务器获取账号下载:http://download.csdn.net/source/540535

 

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/lfywy/archive/2008/07/16/2658623.aspx

posted on 2009-11-23 15:13  云中深海  阅读(1521)  评论(3编辑  收藏  举报