C#实现12306自动登录的方法

依然使用IE9的捕获参数,做了一个12306的登录功能。参照了网上童鞋们的做法。
其他都和前面几篇读取余票、票价一样,不过登录要用到证书的问题,这个参考了一个网上的例子。
不过12306会随时变化,下面的登录不一定一直都能成功。如果12306有变化,大家可以根据变化对代码做修改。总之使用的方法不变,就是捕获参数和url,然后自己补充参数。
效果如下:

项目名称:Test12306AutoLogin;
环境:.net 4.0,Visual studio 2010;
项目图:

核心代码如下,
信任证书代码:

 public class Messenger
  {
    public Messenger()
    {
    }

    public void Register(string message, Action callback)
    {
      this.Register(message, callback, null);
    }

    public void Register<T>(string message, Action<T> callback)
    {
      this.Register(message, callback, typeof(T));
    }

    void Register(string message, Delegate callback, Type parameterType)
    {
      if (String.IsNullOrEmpty(message))
        throw new ArgumentException("'message' cannot be null or empty.");

      if (callback == null)
        throw new ArgumentNullException("callback");

      this.VerifyParameterType(message, parameterType);

      _messageToActionsMap.AddAction(message, callback.Target, callback.Method, parameterType);
    }

    [Conditional("DEBUG")]
    void VerifyParameterType(string message, Type parameterType)
    {
      Type previouslyRegisteredParameterType = null;
      if (_messageToActionsMap.TryGetParameterType(message, out previouslyRegisteredParameterType))
      {
        if (previouslyRegisteredParameterType != null && parameterType != null)
        {
          if (!previouslyRegisteredParameterType.Equals(parameterType))
            throw new InvalidOperationException(string.Format(
              "The registered action's parameter type is inconsistent with the previously registered actions for message '{0}'.\nExpected: {1}\nAdding: {2}",
              message,
              previouslyRegisteredParameterType.FullName,
              parameterType.FullName));
        }
        else
        {
          // One, or both, of previouslyRegisteredParameterType or callbackParameterType are null.
          if (previouslyRegisteredParameterType != parameterType)  // not both null?
          {
            throw new TargetParameterCountException(string.Format(
              "The registered action has a number of parameters inconsistent with the previously registered actions for message \"{0}\".\nExpected: {1}\nAdding: {2}",
              message,
              previouslyRegisteredParameterType == null ? 0 : 1,
              parameterType == null ? 0 : 1));
          }
        }
      }
    }

    public void NotifyColleagues(string message, object parameter)
    {
      if (String.IsNullOrEmpty(message))
        throw new ArgumentException("'message' cannot be null or empty.");

      Type registeredParameterType;
      if (_messageToActionsMap.TryGetParameterType(message, out registeredParameterType))
      {
        if (registeredParameterType == null)
          throw new TargetParameterCountException(string.Format("Cannot pass a parameter with message '{0}'. Registered action(s) expect no parameter.", message));
      }

      var actions = _messageToActionsMap.GetActions(message);
      if (actions != null)
        actions.ForEach(action => action.DynamicInvoke(parameter));
    }

    public void NotifyColleagues(string message)
    {
      if (String.IsNullOrEmpty(message))
        throw new ArgumentException("'message' cannot be null or empty.");

      Type registeredParameterType;
      if (_messageToActionsMap.TryGetParameterType(message, out registeredParameterType))
      {
        if (registeredParameterType != null)
          throw new TargetParameterCountException(string.Format("Must pass a parameter of type {0} with this message. Registered action(s) expect it.", registeredParameterType.FullName));
      }

      var actions = _messageToActionsMap.GetActions(message);
      if (actions != null)
        actions.ForEach(action => action.DynamicInvoke());
    }

    private class MessageToActionsMap
    {
      internal MessageToActionsMap()
      {
      }

      internal void AddAction(string message, object target, MethodInfo method, Type actionType)
      {
        if (message == null)
          throw new ArgumentNullException("message");

        if (method == null)
          throw new ArgumentNullException("method");

        lock (_map)
        {
          if (!_map.ContainsKey(message))
            _map[message] = new List<WeakAction>();

          _map[message].Add(new WeakAction(target, method, actionType));
        }
      }

      internal List<Delegate> GetActions(string message)
      {
        if (message == null)
          throw new ArgumentNullException("message");

        List<Delegate> actions;
        lock (_map)
        {
          if (!_map.ContainsKey(message))
            return null;

          List<WeakAction> weakActions = _map[message];
          actions = new List<Delegate>(weakActions.Count);
          for (int i = weakActions.Count - 1; i > -1; --i)
          {
            WeakAction weakAction = weakActions[i];
            if (weakAction == null)
              continue;

            Delegate action = weakAction.CreateAction();
            if (action != null)
            {
              actions.Add(action);
            }
            else
            {
              // The target object is dead, so get rid of the weak action.
              weakActions.Remove(weakAction);
            }
          }

          // Delete the list from the map if it is now empty.
          if (weakActions.Count == 0)
            _map.Remove(message);
        }

        // Reverse the list to ensure the callbacks are invoked in the order they were registered.
        actions.Reverse();

        return actions;
      }

      internal bool TryGetParameterType(string message, out Type parameterType)
      {
        if (message == null)
          throw new ArgumentNullException("message");

        parameterType = null;
        List<WeakAction> weakActions;
        lock (_map)
        {
          if (!_map.TryGetValue(message, out weakActions) || weakActions.Count == 0)
            return false;
        }
        parameterType = weakActions[0].ParameterType;
        return true;
      }

      readonly Dictionary<string, List<WeakAction>> _map = new Dictionary<string, List<WeakAction>>();
    }

    private class WeakAction
    {

      internal WeakAction(object target, MethodInfo method, Type parameterType)
      {
        if (target == null)
        {
          _targetRef = null;
        }
        else
        {
          _targetRef = new WeakReference(target);
        }

        _method = method;

        this.ParameterType = parameterType;

        if (parameterType == null)
        {
          _delegateType = typeof(Action);
        }
        else
        {
          _delegateType = typeof(Action<>).MakeGenericType(parameterType);
        }
      }

      internal Delegate CreateAction()
      {
        // Rehydrate into a real Action object, so that the method can be invoked.
        if (_targetRef == null)
        {
          return Delegate.CreateDelegate(_delegateType, _method);
        }
        else
        {
          try
          {
            object target = _targetRef.Target;
            if (target != null)
              return Delegate.CreateDelegate(_delegateType, target, _method);
          }
          catch
          {
          }
        }

        return null;
      }

      internal readonly Type ParameterType;
      readonly Type _delegateType;
      readonly MethodInfo _method;
      readonly WeakReference _targetRef;
    }

    readonly MessageToActionsMap _messageToActionsMap = new MessageToActionsMap();
  }

登录的所有方法类:

public class Login12306Manager
  {
    private static readonly Messenger s_messenger = new Messenger();

    public static Messenger SMessenger { get { return s_messenger; } }

    public const string APPEND_MESSAGE = "append_message";

    public static string afterLoginCookie;

    private static string beforLoginCookie;

    static Login12306Manager()
    {
      SetCertificatePolicy();
    }

    /// <summary>
    /// 登 录
    /// </summary>
    public static string Login(string userName,string password, string randomCode)
    {
      string resultHtml = string.Empty;

      try
      {
        string loginRand= DoGetLoginRand();

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create
          (@"https://dynamic.12306.cn/otsweb/loginAction.do?method=login");

        request.Accept = @"text/html, application/xhtml+xml, */*";

        request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";

        request.Referer = @"https://dynamic.12306.cn/otsweb/loginAction.do?method=init";

        request.ContentType = @"application/x-www-form-urlencoded";

        request.Headers[HttpRequestHeader.Cookie] = beforLoginCookie;

        request.Method = "POST";

        byte[] buffer = new byte[0];
        string parameter =
@"loginRand={0}&refundLogin=N&refundFlag=Y&isClick=&form_tk=null&loginUser.user_name={1}&nameErrorFocus=&user.password={2}&passwordErrorFocus=&randCode={3}&randErrorFocus=&NDU0NzY4NA%3D%3D=Nzg4ZDAxMGNkYTZlMTRjZA%3D%3D&myversion=undefined";

        parameter = string.Format(parameter, loginRand, userName, password, randomCode);

        buffer = Encoding.UTF8.GetBytes(parameter);

        request.ContentLength = buffer.Length;
        using (Stream writer = request.GetRequestStream())
        {
          writer.Write(buffer, 0, buffer.Length);

          writer.Flush();
        }

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
          afterLoginCookie = response.GetResponseHeader("Set-cookie");

          using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
          {
            resultHtml = reader.ReadToEnd();

            resultHtml = ProcessLoginResult(resultHtml);
          }
        }
      }
      catch{ }

      return resultHtml;
    }

    /// <summary>
    /// 刷新验证码
    /// </summary>
    public static string RefreshCode()
    {
      string randImageUrl = string.Empty;

      try
      {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(string.Format(@"https://dynamic.12306.cn/otsweb/passCodeNewAction.do?module=login&rand=sjrand",

          new Random().Next(10000, 1000000)));

        request.Accept = @"image/png, image/svg+xml, image/*;q=0.8, */*;q=0.5";

        request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";

        request.Referer = @"https://dynamic.12306.cn/otsweb/loginAction.do?method=init";

        request.Method = "GET";

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
          beforLoginCookie = response.GetResponseHeader("Set-cookie");

          beforLoginCookie = Regex.Replace(beforLoginCookie, "path(?:[^,]+),?", "", RegexOptions.IgnoreCase);

          using (Stream reader = response.GetResponseStream())
          {
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, new Random().Next(10000, 99999) + @"loginRandCode.JPEG");

            using (FileStream file = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write))
            {
              reader.CopyTo(file);
            }

            randImageUrl = path;
          }
        }
      }
      catch { }

      return randImageUrl;
    }

    private static string DoGetLoginRand()
    {
      string loginRand=string.Empty;

      try
      {
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(@"https://dynamic.12306.cn/otsweb/loginAction.do?method=loginAysnSuggest");

        request.Accept = @"application/json, text/javascript, */*";

        request.UserAgent = @"Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)";

        request.Referer = @"https://dynamic.12306.cn/otsweb/loginAction.do?method=init";

        request.Headers[HttpRequestHeader.Cookie] = beforLoginCookie;

        request.Method = "POST";

        byte[] buffer = new byte[0];

        buffer = Encoding.UTF8.GetBytes(string.Empty);

        request.ContentLength = buffer.Length;

        using (Stream writer = request.GetRequestStream())
        {
          writer.Write(buffer, 0, buffer.Length);

          writer.Flush();
        }

        using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
        {
          using (StreamReader reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
          {
            string result = reader.ReadToEnd();

            var loginRandContent = JsonConvert.DeserializeObject<BeforLoginRnad>(result);

            loginRand = loginRandContent.loginRand;
          }
        }
      }
      catch {}

      return loginRand;
    }
    /// <summary>
    /// 处理登录结果
    /// </summary>
    /// <param name="html">登录后返回的html文本</param>
    private static string ProcessLoginResult(string html)
    {
      string m_msgPattern = "message[^\"]+\"(?'message'[^\"]+)\";";

      string m_isLoginPatter = "isLogin\\s*=\\s*(?<val>.+)\n";

      string m_loginUserNamePattern = "u_name\\s*=\\s*['\"](?<name>.+)['\"]";

      if (html.Contains("请输入正确的验证码"))
      {
        return "验证码错误";
      }
      else if (html.Contains("当前访问用户过多"))
      {
        return "当前访问用户过多,请稍后再试...";
      }
      else
      {
        var match0 = Regex.Match(html, m_msgPattern, RegexOptions.Compiled);

        if (match0.Success)
        {
          string text = match0.Groups["message"].Value;

          if (text.Contains("密码") || text.Contains("登录名不存在"))
          {
            return "用户名或者密码错误";
          }
          else
          {
           return text;
          }
        }

        var match = Regex.Match(html, m_isLoginPatter, RegexOptions.Compiled);

        if (match.Success && (match.Groups["val"].Value.Trim().ToLower() == "true"))
        {
          match = Regex.Match(html, m_loginUserNamePattern, RegexOptions.Compiled);
          if (match.Success)
          {
            string name = match.Groups["name"].Value;

            return "登录成功:" + name;
          }
          else
          {
            return "登录失败,未知错误";
          }
        }
        else
        {
          return "登录失败!!!";
        }
      }
    }

    /// <summary>
    /// Sets the cert policy.
    /// </summary>
    private static void SetCertificatePolicy()
    {
      ServicePointManager.ServerCertificateValidationCallback
            += RemoteCertificateValidate;
    }

    /// <summary>
    /// Remotes the certificate validate.
    /// </summary>
    private static bool RemoteCertificateValidate(
      object sender, X509Certificate cert,
      X509Chain chain, SslPolicyErrors error)
    {
      SMessenger.NotifyColleagues(APPEND_MESSAGE, "信任任何证书...");
      return true;
    }
  }

  public class BeforLoginRnad
  {
    public string loginRand { get; set; }

    public string randError { get; set; }
  }

注意登录时,主要的正文是:

string parameter =
@"loginRand={0}&refundLogin=N&refundFlag=Y&isClick=&form_tk=null&loginUser.user_name={1}&nameErrorFocus=&user.password={2}&passwordErrorFocus=&randCode={3}&randErrorFocus=&NDU0NzY4NA%3D%3D=Nzg4ZDAxMGNkYTZlMTRjZA%3D%3D&myversion=undefined",它有三个参数,登录时的随机码,用户名,密码和验证码组成。

调用如下:

前台wpf代码:

<Window x:Class="Test12306AutoLogin.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="MainWindow">
  <StackPanel>
    <Grid>
      <Grid.Resources>
        <Style TargetType="TextBlock">
          <Setter Property="FontFamily" Value="Microsoft YaHei"/>
          <Setter Property="FontSize" Value="20"/>
          <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>

        <Style TargetType="TextBox">
          <Setter Property="FontSize" Value="20"/>
          <Setter Property="MinWidth" Value="300"/>
          <Setter Property="Height" Value="50"/>
          <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>

        <Style TargetType="PasswordBox">
          <Setter Property="FontSize" Value="20"/>
          <Setter Property="MinWidth" Value="300"/>
          <Setter Property="Height" Value="50"/>
          <Setter Property="VerticalAlignment" Value="Center"/>
        </Style>
      </Grid.Resources>
      <Grid.RowDefinitions>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="auto"/>
        <RowDefinition Height="auto"/>
      </Grid.RowDefinitions>

      <Grid.ColumnDefinitions>
        <ColumnDefinition Width="auto"/>
        <ColumnDefinition Width="auto"/>
      </Grid.ColumnDefinitions>

      <TextBlock Grid.Row="0" Grid.Column="0" Text="用户名:"/>
      <TextBox Grid.Row="0" Grid.Column="1" x:Name="txtUserName"/>

      <TextBlock Grid.Row="1" Grid.Column="0" Text="密 码:"/>
      <PasswordBox Grid.Row="1" Grid.Column="1" x:Name="txtPassword"/>

      <TextBlock Grid.Row="3" Grid.Column="0" Text="验证码"/>
      <StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal"
            VerticalAlignment="Center">
        <TextBox x:Name="txtRandCode" Width="150"/>
        <Image x:Name="imageRandCode" Width="70"/>
        <Button Content="刷新验证码" Height="30" Width="80" Click="ButtonRefreshRandCode_Click" />
      </StackPanel>
    </Grid>

    <Button Content="登 录" Width="150" Height="50" Click="ButtonLogin_Click" />

    <RichTextBox x:Name="rtxResultContent" MinHeight="200"/>

  </StackPanel>
</Window>

后台代码:

public partial class MainWindow : Window
  {
    public MainWindow()
    {
      InitializeComponent();

      this.Loaded += new RoutedEventHandler(MainWindow_Loaded);
    }

    void MainWindow_Loaded(object sender, RoutedEventArgs e)
    {
      DoRefreshRandCode();
    }

    private void DoRefreshRandCode()
    {
      string imageRandUrl = Login12306Manager.RefreshCode();

      if (File.Exists(imageRandUrl))
      {
        ImageSource src = (ImageSource)(new ImageSourceConverter().ConvertFromString(imageRandUrl));

        this.imageRandCode.Source = src;
      }

      this.txtRandCode.Text = string.Empty;
    }

    /// <summary>
    /// 登录
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ButtonLogin_Click(object sender, RoutedEventArgs e)
    {
      string userName = this.txtUserName.Text;

      string password = this.txtPassword.Password;

      string randCode = this.txtRandCode.Text;

      if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password) || string.IsNullOrEmpty(randCode))
      {
        MessageBox.Show("请填写完整信息");

        return;
      }

      string html = Login12306Manager.Login(userName, password, randCode);

      System.Windows.Documents.FlowDocument doc = this.rtxResultContent.Document;

      doc.Blocks.Clear();

      this.rtxResultContent.AppendText(html);
    }

    /// <summary>
    /// 刷新验证码
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void ButtonRefreshRandCode_Click(object sender, RoutedEventArgs e)
    {
      DoRefreshRandCode();
    }
  }

以上就是本文的全部内容,希望对大家的学习有所帮助。

(0)

相关推荐

  • C# Winform中实现主窗口打开登录窗口关闭的方法

    在使用C#进行Winform编程时,我们经常需要使用一个登录框来进行登录,一旦输入的用户名密码登录成功,这时登录窗口应该关闭,而且同时打开主程序窗口.该如何来实现呢? 乍一想,很简单啊,打开主窗口就用主窗口的Show()方法,而关闭登录窗口就用登录窗口的Close()方法即可.即代码如下: Program.cs中代码: 复制代码 代码如下: Application.Run(new FormLogin()); 登录窗口(FormLogin)代码: 复制代码 代码如下: private void b

  • C#实现简单的登录界面

    首先我们来看一个简单的制作过程 打开visual 2010,新建窗体,既然是登录窗口,那么就不让它出现最大化.最小化以及拖拉大小功能(上一节已经提到过怎么设置大小),如图所示,甚至窗体的Text属性值为"登录窗口",大小随意. 创建窗体之后就开始界面详细的组件布局了,主要是在左边拖拉控件,然后放到窗体中去,定义属性值.这些都比较简单. 到了代码响应阶段,双击登录按钮,进入代码视图: private void button1_Click(object sender, EventArgs

  • c#通过进程调用cmd判断登录用户权限代码分享

    复制代码 代码如下: /// <summary>/// 应用程序的主入口点./// </summary>[STAThread]static void Main(){ if (RunCmd("net localgroup administrators").IndexOf(System.Environment.UserName) >= 0)    { //顺利执行.    }    else    {        //报错提示系统不是管理员用户登录,容易导致

  • C#.NET实现网页自动登录的方法

    本文实例讲述了C#.NET实现网页自动登录的方法.分享给大家供大家参考.具体如下: 用C#语言编写一个Windows Form应用程序,实现自动登录一个特定的页面. 下面以自动登录:http://localhost/Web/Login.aspx 作为例子,讲解如何模拟手工输入用户名密码并点击登录,实现自动登录. 新建一个C#应用程序,给应用程序起个名字,如AutoLogin,在窗体中添加一个TextBox.Button,及WebBrowser控件,并为WebBrowser控件添加webBrows

  • c#调用存储过程实现登录界面详解

    1,创建存储过程 复制代码 代码如下: create proc Pro_Login(@UserName nvarchar(10),@PassWord nvarchar(10))as select * from [User] UserName=@UserName and PassWord=@PassWord 2,通过类是实现配置数据库字符串连接 复制代码 代码如下: class ConnectionString{public static string conStr = "Data Source=

  • asp.net c#采集需要登录页面的实现原理及代码

    首先说明:代码片段是从网络获取,然后自己修改.我想好的东西应该拿来分享. 实现原理:当我们采集页面的时候,如果被采集的网站需要登录才能采集.不管是基于Cookie还是基于Session,我们都会首先发送一个Http请求头,这个Http请求头里面就包含了网站需要的Cookie信息.当网站接收到发送过来的Http请求头时,会从Http请求头获取相关的Cookie或者Session信息,然后由程序来处理,决定你是否有权限访问当前页面. 好了,原理搞清楚了,就好办了.我们所要做的仅仅是在采集的时候(或者

  • C#可用于登录验证码的四位随机数生成方法

    本文实例讲述了C#可用于登录验证码的四位随机数生成方法.分享给大家供大家参考.具体实现方法如下: 这里提供了两种方法,调用其一即可: 复制代码 代码如下: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace SJ_random {     class Class_main     {        

  • div弹出层的ajax登录(Jquery版+c#)

    页面初始化,界面如图所示: Server name文本框获取焦点时候,界面如图所示(这里可以改成你登录的验证码): 可以加载SQL Server服务列表,也是我的简易SQL查询分析器评论中静夜妙思给予的方法,非常感谢! 加载列表如下图所示: 可以随意地点击添加到Server name中,登录时截图所示: 文本框验证都写好了!还有Authentication验证方式,windows验证下面Login,Password文本框禁掉!由于时间原因,不上图了 demo.html(全部前台代码,js/css

  • C#实现12306自动登录的方法

    依然使用IE9的捕获参数,做了一个12306的登录功能.参照了网上童鞋们的做法. 其他都和前面几篇读取余票.票价一样,不过登录要用到证书的问题,这个参考了一个网上的例子. 不过12306会随时变化,下面的登录不一定一直都能成功.如果12306有变化,大家可以根据变化对代码做修改.总之使用的方法不变,就是捕获参数和url,然后自己补充参数. 效果如下: 项目名称:Test12306AutoLogin: 环境:.net 4.0,Visual studio 2010: 项目图: 核心代码如下, 信任证

  • asp.net利用cookie保存用户密码实现自动登录的方法

    本文实例讲述了asp.net利用cookie保存用户密码实现自动登录的方法.分享给大家供大家参考.具体分析如下: 在asp.net中可以用cookie保存用户的帐户密码实现自动登录的功能,但是需要强调一下,cookie在客户端保存,是不安全的,推荐使用md5加密保存. 下面分析一下在asp.net中cookie的创建.提取与销毁的方法: 创建cookie 复制代码 代码如下: //向客户端写入Cookie HttpCookie hcUserName1 = new HttpCookie("unam

  • php利用cookie实现自动登录的方法

    本文实例讲述了php利用cookie实现自动登录的方法.分享给大家供大家参考.具体实现方法如下: html前端页面代码如下: 复制代码 代码如下: <html>   <head>   <title>enter password</title>   </head>   <body>   <form name="forml" method="post" action="cookieb

  • Selenium获取登录Cookies并添加Cookies自动登录的方法

    本章中用到的关键方法如下: get_cookies(): 获得所有cookie信息. get_cookie(name): 返回字典的key为"name"的cookie信息. add_cookie(cookie_dict): 添加cookie."cookie_dict"指字典对象,必须有name 和value 值. delete_cookie(name,optionsString):删除cookie信息."name"是要删除的cookie的名称,&

  • Win 2003两种自动登录的方法

    如何快速的进入Windows 2003操作系统呢?在本文中我们将介绍两种快速登陆Windows 2003操作系统的方法: 一种方法比较简单,您只需单击"开始|运行",并在输入框中键入"control userpasswords2",这样就可以在"用户账户"管理窗口中清除"要使用本机,用户必须输入密码"复选项的选中状态,然后按下键盘的"Ctrl+Shift+A",将会得到一个"自动登录"的

  • putty实现自动登录的方法(ssh和ssh2)

    1.登录主机并输入ssh-keygen -t rsa 提示Enter file in which to save the key (/root/.ssh/id_rsa): 输入/root/.ssh/sea_rsa 根据提示输入相关路径名和文件名并生成两个文件(之后的两个选项直接回车) 2.把那个没有.pub的文件copy出来用puttygen转换一下生成windows下putty可用的key(这里指sea_rsa,选择puttygen的Conversions的Import key(这里指sea_

  • java使用Filter实现自动登录的方法

    本文实例为大家分享了java实现自动登录的具体代码,供大家参考,具体内容如下 当你勾选(记住登录状态),用cookie保存用户名和密码.不勾选,cookie失效. 所有的页面都要经过autoLoginFilter.java 的过滤器,在这类中,必须要判断cookies不为null,获得所有的cookie,得到name为user的cookie,进行用户名和密码的验证,如果不为null,则将user存入session. 在LoginServlet.java中,获得username和password参

  • Yii2框架实现登录、退出及自动登录功能的方法详解

    本文实例讲述了Yii2框架实现登录.退出及自动登录功能的方法.分享给大家供大家参考,具体如下: 自动登录的原理很简单.主要就是利用cookie来实现的 在第一次登录的时候,如果登录成功并且选中了下次自动登录,那么就会把用户的认证信息保存到cookie中,cookie的有效期为1年或者几个月. 在下次登录的时候先判断cookie中是否存储了用户的信息,如果有则用cookie中存储的用户信息来登录, 配置User组件 首先在配置文件的components中设置user组件 'user' => [ '

  • YII2自动登录Cookie总是失效的解决方法

    前言 最近做Yii2自动登录功能,发现即使开启了Yii2的自动登录配置功能,浏览器关闭后,再次打开浏览器还是处于非登录状态. 网上查询资料基本没有相同情况. 查询登录源码: protected function sendIdentityCookie($identity, $duration) { $cookie = new Cookie($this->identityCookie); $cookie->value = json_encode([ $identity->getId(), $

随机推荐