Skip to content

Instantly share code, notes, and snippets.

@jjam3774
Last active July 29, 2020 23:06
Show Gist options
  • Save jjam3774/eae159be18f3dfc6c3ad to your computer and use it in GitHub Desktop.
Save jjam3774/eae159be18f3dfc6c3ad to your computer and use it in GitHub Desktop.
Example of using PyCurl.....
#!/usr/bin/python
import urllib2
import json
import getpass
import sys
def rest_uptime(password):
username = raw_input("Username: ")
password = getpass.getpass('Password: ')
password_mgr = urllib2.HTTPPasswordMgrWithDefaultRealm()
link = "https://nmmon2:9997/api/v1/groups/2/status"
authmgr = urllib2.HTTPBasicAuthHandler(password_mgr)
authmgr.add_password(None, "https://nmmon2:9997/api/v1/groups/2/status", username.strip(), password)
opener = urllib2.build_opener(authmgr)
urllib2.install_opener(opener)
try:
req = urllib2.Request(link)
handle = urllib2.urlopen(req)
print("Authentication done..")
for i in handle.readlines():
for j in i.split(','):
print( json.dumps(j, sort_keys=True, indent=14, separators=(',', ': ')))
except IOError, e:
if hasattr(e, 'code'):
print 'Error code - %s.' % e.code
elif hasattr(e, 'reason'):
print "Error object reason:", e.reason
sys.exit()
def curl_get():
import pycurl, json
import cStringIO
import getpass
uptime_url = "https://nmmon2:9997/api/v1/groups/"
########################
# Define Username and Password like so username:password
########################
user_pwd = "nmjlj23:GangnumStyle"
########################
# Create handler for the info from page
########################
buf = cStringIO.StringIO()
########################
# Create object to perform changes to link(SSL, HEADER INFO, etc..)
########################
c = pycurl.Curl()
c.setopt(pycurl.USERAGENT, "Mozilla/5.0 (compatible; pycurl)")
########################
#Define SSL for Link
########################
c.setopt(pycurl.SSL_VERIFYPEER, 0)
c.setopt(pycurl.SSL_VERIFYHOST, 2)
########################
#Process URL
########################
c.setopt(pycurl.URL, uptime_url)
########################
#Pass Userid and Password
########################
c.setopt(pycurl.USERPWD, user_pwd)
########################
#Turn on debug to see session progress
########################
c.setopt(pycurl.VERBOSE, True)
########################
# Pass Page Content to buffer
########################
print c.setopt(c.WRITEFUNCTION, buf.write)
c.setopt(c.VERBOSE, True)
########################
# Perform Request
########################
print c.perform()
########################
# Print the retrieved info to the screen
########################
print buf.getvalue()
#rest_uptime(password)
curl_get()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment