2009-08-15 203 views
5

我需要在wordpress管理面板中以編程方式執行一些操作,但無法管理如何使用C#和HttpWebRequest登錄到Wordpress。如何以編程方式登錄wordpress?

這裏是我做的:

private void button1_Click(object sender, EventArgs e) 
     { 
      string url = "http://localhost/wordpress/wp-login.php"; 
      HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); 
      CookieContainer cookies = new CookieContainer(); 

      SetupRequest(url, request, cookies); 
      //request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 
      //request.Headers["Accept-Language"] = "uk,ru;q=0.8,en-us;q=0.5,en;q=0.3"; 
      //request.Headers["Accept-Encoding"] = "gzip,deflate"; 
      //request.Headers["Accept-Charset"] = "windows-1251,utf-8;q=0.7,*;q=0.7"; 


      string user = "test"; 
      string pwd = "test"; 

      request.Credentials = new NetworkCredential(user, pwd); 

      string data = string.Format(
       "log={0}&pwd={1}&wp-submit={2}&testcookie=1&redirect_to={3}", 
       user, pwd, 
       System.Web.HttpUtility.UrlEncode("Log In"), 
       System.Web.HttpUtility.UrlEncode("http://localhost/wordpress/wp-admin/")); 

      SetRequestData(request, data); 

      ShowResponse(request); 
} 

private static void SetupRequest(string url, HttpWebRequest request, CookieContainer cookies) 
     { 
      request.CookieContainer = cookies; 
      request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; uk; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"; 
      request.KeepAlive = true; 
      request.Timeout = 120000; 
      request.Method = "POST"; 
      request.Referer = url; 
      request.ContentType = "application/x-www-form-urlencoded"; 
     } 

     private void ShowResponse(HttpWebRequest request) 
     { 
      HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
      responseTextBox.Text = (((HttpWebResponse)response).StatusDescription); 
      responseTextBox.Text += "\r\n"; 
      StreamReader reader = new StreamReader(response.GetResponseStream()); 
      responseTextBox.Text += reader.ReadToEnd(); 
     } 

     private static void SetRequestData(HttpWebRequest request, string data) 
     { 
      byte[] streamData = Encoding.ASCII.GetBytes(data); 
      request.ContentLength = streamData.Length; 

      Stream dataStream = request.GetRequestStream(); 
      dataStream.Write(streamData, 0, streamData.Length); 
      dataStream.Close(); 
     } 

但不幸的是在性反應,我得到的登錄頁面的唯一HTML源代碼,似乎cookie不包含會話ID。我在該代碼之後執行的所有請求也返回登錄頁面的HTML源,因此我可以認爲它不能正確登錄。

任何人都可以幫助我解決這個問題或給工作的例子嗎?


我想實現的主要目標是在Nextgen Gallery插件中爲Wordpress掃描新圖像。有XML-RPC的方式嗎?

在此先感謝。

回答

1

感謝大家。我管理如何使它只在使用套接字時才起作用。 WordPress發送幾個Set-Cookie標題,但HttpWebRequest只處理這樣的標題的一個實例,所以一些cookies丟失。使用套接字時,我可以獲取所有需要的cookie並登錄到管理面板。

+1

某些代碼不會是壞的其他人們也許正在尋找解決方案(像我一樣)。多數民衆贊成在一個論壇... – C4u 2015-03-14 17:46:22

+0

如此殘酷!爲什麼解決方案不在那裏? – 2015-08-27 04:36:47

+0

這是公認的答案?沒有代碼? – DidIReallyWriteThat 2016-11-06 00:44:29

1

我發現你的代碼沒有明顯的問題,對不起。但Wordpress有一個XML-RPC接口,必須在管理界面中啓用。我爲這個界面編寫了一些python腳本,它像一個魅力一樣工作。

0

我試着用我的WordPress.com帳戶(使用SSL保護)。我發現最簡單的方法是使用.NET套接字獲取HTTP「Set-Cookie」標頭,然後將標頭解析爲.NET Cookie對象,然後使用CookieContainer和HttpWebRequest的Cookie。

在套接字上使用SSL最簡單的方法是通過綁定到套接字的NetworkStream實現SslStream。

實施例:

private void LogIn() 
    { 
     string fulladdress = "hostname.wordpress.com"; 
     string username = HttpUtility.UrlEncode("username"); 
     string password = HttpUtility.UrlEncode("password"); 

     string formdata = "log={0}&pwd={1}&redirect_to=http%3A%2F%2F{2}%2Fwp-admin%2F&testcookie=1"; 
     formdata = string.Format(formdata, username, password, fulladdress); 
     IPHostEntry entry = Dns.GetHostEntry(fulladdress); 


     Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP); 
     s.Connect(entry.AddressList[0], 443); 

     NetworkStream ns = new NetworkStream(s); 

     System.Net.Security.SslStream ssl = new System.Net.Security.SslStream(ns); 
     byte[] data = Encoding.UTF8.GetBytes(String.Format(WpfApplication2.Properties.Resources.LogRequest, "https://" + fulladdress, fulladdress, form.Length, username, password)); 

     ssl.AuthenticateAsClient(fulladdress); 
     ssl.Write(data, 0, data.Length); 

     StringBuilder sb = new StringBuilder(); 
     byte[] resp = new byte[128]; 
     int i = 0; 
     while (ssl.Read(resp, 0, 128) > 0) 
     { 
      sb.Append(Encoding.UTF8.GetString(resp)); 
     } 

     List<String> CookieHeaders = new List<string>(); 
     foreach (string header in sb.ToString().Split("\n\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)) 
     { 
      if (header.StartsWith("Set-Cookie")) 
      { 
       CookieHeaders.Add(header.Replace("Set-Cookie: ", "")); 
      } 
     } 

     CookieContainer jar = new CookieContainer(); 
     foreach (string cook in CookieHeaders) 
     { 
      string name, value, path, domain; 
      name = value = path = domain = ""; 

      string[] split = cook.Split(';'); 
      foreach (string part in split) 
      { 
       if (part.StartsWith(" path=")) 
       { 
        path = part.Replace(" path=", ""); 
       } 
       if (part.StartsWith(" domain=")) 
       { 
        domain = part.Replace(" domain=", ""); 
       } 
       if (!part.StartsWith(" path=") && !part.StartsWith(" domain=") && part.Contains("=")) 
       { 
        name = part.Split('=')[0]; 
        value = part.Split('=')[1]; 
       } 
      } 

      jar.Add(new Cookie(name, value, path, domain)); 
     } 

     HttpWebRequest req = (HttpWebRequest)WebRequest.Create("https://" + fulladdress + "/wp-admin/index.php"); 
     req.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3"; 
     req.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; 
     req.KeepAlive = false; 
     req.AllowAutoRedirect = false; 
     req.Referer = "https://" + fulladdress + "/wp-login.php"; 
     req.ContentType = "application/x-www-form-urlencoded"; 
     req.CookieContainer = jar; 
     req.AllowAutoRedirect = true; 
     req.AutomaticDecompression = DecompressionMethods.GZip; 
     req.Method = "GET"; 
     req.Timeout = 30000; 

     HttpWebResponse response = (HttpWebResponse)req.GetResponse(); 

     using (System.IO.StreamReader sr = new System.IO.StreamReader(response.GetResponseStream(), Encoding.UTF8)) 
     { 
      MessageBox.Show(sr.ReadToEnd()); 
     } 
    } 

的代碼不是非常有效的,但它示出了登錄到管理界面的過程。

希望它能幫助:)

1
NameValueCollection loginData = new NameValueCollection(); 
loginData.Add("username", "your_username"); 
loginData.Add("password", "your_password"); 

WebClient client = new WebClient(); 
string source = Encoding.UTF8.GetString(client.UploadValues("http://www.site.com/login", loginData)); 

string cookie = client.ResponseHeaders["Set-Cookie"]; 
3

我不知道別人會有所幫助,但我只是用WordPress的API登錄。我創建了一個用戶(CRON_USR)誰「的日誌中「在晚上作爲cron工作的一部分,並完成一些任務。 的代碼是這樣的:

require(dirname(__FILE__) . '/wp-load.php'); 
$user = wp_authenticate(CRON_USR, CRON_PWD); 
wp_set_auth_cookie($user->ID, true, $secure_cookie); //$secure_cookie is an empty string 
do_action('wp_login', CRON_USR); 
wp_redirect('http://www.mysite.com/wp-admin/'); 
5

由於WordPress的執行重定向,離開頁面(重定向)防止從的WebRequest得到適當的cookie。

爲了獲得相關的cookie,必須防止重定向。

request.AllowAutoRedirect = false; 

比使用cookie-conatainer進行登錄。

看到下面的代碼: (基於阿爾巴哈利的C#書爲例)

 string loginUri = "http://www.someaddress.com/wp-login.php"; 
     string username = "username"; 
     string password = "pass"; 
     string reqString = "log=" + username + "&pwd=" + password; 
     byte[] requestData = Encoding.UTF8.GetBytes(reqString); 

     CookieContainer cc = new CookieContainer(); 
     var request = (HttpWebRequest)WebRequest.Create(loginUri); 
     request.Proxy = null; 
     request.AllowAutoRedirect = false; 
     request.CookieContainer = cc; 
     request.Method = "post"; 

     request.ContentType = "application/x-www-form-urlencoded"; 
     request.ContentLength = requestData.Length; 
     using (Stream s = request.GetRequestStream()) 
      s.Write(requestData, 0, requestData.Length); 

     using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) 
     { 
      foreach (Cookie c in response.Cookies) 
       Console.WriteLine(c.Name + " = " + c.Value); 
     } 

     string newloginUri = "http://www.someaddress.com/private/"; 
     HttpWebRequest newrequest = (HttpWebRequest)WebRequest.Create(newloginUri); 
     newrequest.Proxy = null; 
     newrequest.CookieContainer = cc; 
     using (HttpWebResponse newresponse = (HttpWebResponse)newrequest.GetResponse()) 
     using (Stream resSteam = newresponse.GetResponseStream()) 
     using (StreamReader sr = new StreamReader(resSteam)) 
      File.WriteAllText("private.html", sr.ReadToEnd()); 
     System.Diagnostics.Process.Start("private.html"); 
0

TomerBu對我來說最好的答案,但缺了點什麼。

在他的代碼,remplace:

foreach (Cookie c in response.Cookies) 
      Console.WriteLine(c.Name + " = " + c.Value); 

通過

if (response.Cookies != null) 
    { 
     foreach (Cookie currentcook in response.Cookies) 
      request.CookieContainer.Add(currentcook); //This is the key !!! 
    } 

下一頁爲未來的危機的要求,你必須重用的CookieContainer。

0

爲了以編程方式登錄到WordPress的共享主機(的cPanel),TomerBu's答案的伎倆給我一個增加:UserAgent必須定義如下

... 
request.Proxy = null; 
request.AllowAutoRedirect = false; 
request.CookieContainer = cc; 
request.Method = "post"; 


// Add UserAgent 
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:2.0.1) Gecko/20100101 Firefox/4.0.1";