Today there is a need to access the internal CMDB via cookies to obtain information such as machines. Surf the internet for a bit of usage. Record it
Direct access with a password
#-*-Coding:utf-8-*-#!/usr/bin/pythonimport urllib2import urllibimport cookielibimport reauth_url = ' http://a.test.co M/user/login ' Home_url = ' http://a.test.com/cmdb/hosts/'; # login username and password data={"username": "AAA", "Password": "BBB"}# Urllib encoding Post_data=urllib.urlencode (data) # Send header information headers ={"Host": "A.test.com", "Referer": "Http://a.test.com"}# Initializes a cookiejar to handle the cookiecookiejar=cookielib. Cookiejar () # Instantiates a global Openeropener=urllib2.build_opener (urllib2. Httpcookieprocessor (Cookiejar) # get COOKIEREQ=URLLIB2. Request (auth_url,post_data,headers) result = Opener.open (req) # Access to home page automatically with cookie information Iresult = Opener.open (home_url) # Show results Print Iresult.read ()
Because there is no specific account to read, only the use of their own personal account. So don't want to keep the password in the file. Ready to produce a cookie file, followed by this cookie file for access
Production of cookie Files first
# -*- coding: utf-8 -*-# !/usr/bin/pythonimport urllib2import urllibimport cookielibimport reauth_url = ' http://a.test.com/user/login ' # login username and password data={ "username": "AAA", "password": "BBB"}# urllib encode Post_data=urllib.urlencode (data) # Send header information headers ={ "Host": "A.test.com", "Referer": "http://a.test.com"}# Initializes a cookiejar to handle the cookiecookiejar=cookielib. Cookiejar () # instantiates a global Openeropener=urllib2.build_opener (urllib2. Httpcookieprocessor (Cookiejar)) req = urllib2. Request (auth_url, post_data, headers) req.add_header (' user-agent ', ' Mozilla/4.0 (compatible; msie 6.0; windows nt 5.1) ' filename = ' Cookie.txt ' Ckjar = cookielib. Mozillacookiejar (filename) ckproc = urllib2. Httpcookieprocessor (Ckjar) Opener = urllib2.build_opener (Ckproc) f = opener.open (req) htm = f.read () F.close () Ckjar.save (ignore_discard=true, ignore_expires=true)
The second step, through this cookie file access, the first step after the production of the cookie file, the script can be cleaned out
#-*-Coding:utf-8-*-#!/usr/bin/pythonimport cookielibimport urllib2import sysreload (SYS) sys.setdefaultencoding (' Utf-8 ') cookie=cookielib. Mozillacookiejar () cookie.load (' Cookie.txt ', ignore_expires=true,ignore_discard=true) req=urllib2. Request (' http://a.test.com/cmdb/hosts/') Opener=urllib2.build_opener (urllib2. Httpcookieprocessor (Cookie)) Urllib2.install_opener (opener) Response=urllib2.urlopen (req) print response.read ()
This article is from my blog blog, so be sure to keep this source http://lschao.blog.51cto.com/7814743/1945383
Python requests a Web site by generating a cookie file and using a cookie file