I am new to python and I am trying to create a chat server in python using socket. In my server i want to encrypt and decrypt the message sended from the client to the sever.I am trying to create a key from the server then send it to the client but i got this error: "'function' object is not iterable" . I am following this guide : https://riptutorial.com/python/topic/8710/sockets-and-message-encryption-decryption-between-client-and-server.
Here are the code that generate the error:
key_128 = os.urandom(16)
#encrypt CTR MODE session key
en = AES.new(key_128,AES.MODE_CTR,counter = lambda:key_128)
encrypto = en.encrypt(key_128)
and this is the error :
Traceback (most recent call last):
File "test.py", line 4, in <module>
en = AES.new(key_128,AES.MODE_CTR,counter = lambda:key_128)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\site-packages\Crypto\Cipher\AES.py", line 232, in new
return _create_cipher(sys.modules[__name__], key, mode, *args, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\site-packages\Crypto\Cipher\__init__.py", line 79, in _create_cipher
return modes[mode](factory, **kwargs)
File "C:\Users\Admin\AppData\Local\Programs\Python\Python37\lib\site-packages\Crypto\Cipher\_mode_ctr.py", line 366, in _create_ctr_cipher
_counter = dict(counter)
TypeError: 'function' object is not iterable
I tried to run this guide on python 2.7 and it run ok. But i run on python 3 it has error. Can some one explain why and help me fix this?
Update :
I am using pycryptodome instead of Pycrypto because i cant install Pycrypto in my pc.
I did some researches how to fix this. There is the link that said the error is caused by conflict between python-crypto in lib and local/lib ... But i dont think it is. Here is the link https://github.com/nccgroup/Winpayloads/issues/21
Per the documentation:
counter : (object) – Instance of Crypto.Util.Counter, which allows full customization of the counter block. This parameter is incompatible to both nonce and initial_value.
counter in this context is an anonymous function (a lambda), but not an instance of Crypto.Util.Counter. Given key_128 = os.urandom(16) - key_128 is a string.
Related
I've been trying to follow the examples and documentation for the python ad_manager library for the google ads API, but I haven't been able to complete a successful request. I currently have my developer token, client_id, client_secret, and refresh_token in my google ads YAML file, but I'm constantly getting the error "argument should be integer or bytes-like object, not 'str'" when calling the function WaitForReport following the example code below. I was wondering if anyone had any advice on how I could tackle this issue.
import tempfile
# Import appropriate modules from the client library.
from googleads import ad_manager
from googleads import errors
def main(client):
# Initialize a DataDownloader.
report_downloader = client.GetDataDownloader(version='v202111')
# Create report job.
report_job = {
'reportQuery': {
'dimensions': ['COUNTRY_NAME', 'LINE_ITEM_ID', 'LINE_ITEM_NAME'],
'columns': ['UNIQUE_REACH_FREQUENCY', 'UNIQUE_REACH_IMPRESSIONS',
'UNIQUE_REACH'],
'dateRangeType': 'REACH_LIFETIME'
}
}
try:
# Run the report and wait for it to finish.
report_job_id = report_downloader.WaitForReport(report_job)
except errors.AdManagerReportError as e:
print('Failed to generate report. Error was: %s' % e)
# Change to your preferred export format.
export_format = 'CSV_DUMP'
report_file = tempfile.NamedTemporaryFile(suffix='.csv.gz', delete=False)
# Download report data.
report_downloader.DownloadReportToFile(
report_job_id, export_format, report_file)
report_file.close()
# Display results.
print('Report job with id "%s" downloaded to:\n%s' % (
report_job_id, report_file.name))
if __name__ == '__main__':
# Initialize client object.
ad_manager_client = ad_manager.AdManagerClient.LoadFromStorage()
main(ad_manager_client)
Edit:
Below is the stack trace:
Traceback (most recent call last):
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/googleads/common.py", line 984, in MakeSoapRequest
return soap_service_method(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/zeep/proxy.py", line 46, in __call__
return self._proxy._binding.send(
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/zeep/wsdl/bindings/soap.py", line 135, in send
return self.process_reply(client, operation_obj, response)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/zeep/wsdl/bindings/soap.py", line 229, in process_reply
return self.process_error(doc, operation)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/zeep/wsdl/bindings/soap.py", line 317, in process_error
raise Fault(
zeep.exceptions.Fault: Unknown fault occured
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "google_ads.py", line 72, in <module>
main(ad_manager_client)
File "google_ads.py", line 33, in main1
report_job_id = report_downloader.WaitForReport(report_job)
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/googleads/ad_manager.py", line 784, in WaitForReport
report_job_id = service.runReportJob(report_job)['id']
File "/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/googleads/common.py", line 989, in MakeSoapRequest
underlying_exception = e.detail.find(
TypeError: argument should be integer or bytes-like object, not 'str'
In your YAML file, do you have your account number in quotes? (either single or double?)
Additionally, I would highly recommend not going with this API if you have the option. It will be sunset in April and will no longer work. The newer google ads API (as opposed to the AdWords API) is available, stable and much easier to work with. The ad manager examples are good too.
The problem seems to be that zeep raises a WebFault which includes the returned XML response as a string in zeep.Fault.detail.
Somewhat counter-intuitive, this attribute is not a string, but a bytes sequence because zeep.wsdl.utils.etree_to_string calls etree.tostring() with encoding="utf-8" instead of encoding="unicode"—the latter would make sure it's a proper string.
googleads then tries to look for specific error strings inside the XML using find(), but even though find() is defined both on str and bytes, the type of the substring to look for needs to align.
Thus, in
underlying_exception = e.detail.find(
'{%s}ApiExceptionFault' % self._GetBindingNamespace())
bytes.find() is called with a str argument, causing the ValueError you experience.
I'd argue that zeep.wsdl.utils.etree_to_string() should be adjusted to actually return a str instead of bytes. You could try opening an issue on Zeep's Github repository.
i'm working on a authentication system with raspberry pi with the Fingerprint Scanner - TTL (GT-511C3) and i have a function that create a template and returns as result the following :
I want to extract only th data part so i did like this : response 1['Data']
but when i print it i get this :
i added this as header of my file :
reload(sys)
sys.setdefaultencoding('utf8')
and i tried a couple of solutions i found in the forum but i couldn't find one that works with me.
my problem is when i try to compare the created template with the ones already in the database of the scanner with a function called IdentifyTemplate and takes as a parameter a template it gives me the following error :
Traceback (most recent call last):
File "finger.py", line 169, in
indetifyResponse = f.IdentifyTemplate(makeTemplateResponse)
File "/home/pi/Desktop/fingerpi/fingerpi/fingerpi.py", line 213, in
IdentifyTemplate
if self.sendData(template, 498):
File "/home/pi/Desktop/fingerpi/fingerpi/fingerpi.py", line 53, in sendData
packet = encode_data_packet(data, data_len, device_id = self.device_id)
File "/home/pi/Desktop/fingerpi/fingerpi/base.py", line 72, in
encode_data_packet
data # Data to be sent
struct.error: argument for 's' must be a string
i suspect that the problem is comming from that Data that i'm trying to print.
Any help is much appreciated. My Python version is 2.7.13
I'm facing problem when pushing using pygit2 v0.21.3 .
here is my code :
import pygit2 as git
repo = git.Repository("path/to/my/repo.git") # just for testing,it will not be local
for rem in repo.remotes:
rem.push_url = rem.url
rem.credentials = git.UserPass("user","passowrd")
sig = git.Signature("user","user#example.com")
rem.push('refs/heads/master',signature=sig)
# in v0.22.0 it will be like below
# rem.push(['refs/heads/master'],signature=sig)
But,I always received this message :
Traceback (most recent call last):
File "C:\test.py", line 9, in <module>
rem.push('refs/heads/master',signature=sig)
File "C:\Python34\lib\site-packages\pygit2-0.21.3-py3.4-win32.egg\pygit2\remote.py",line 353, in push
err = C.git_push_update_tips(push, ptr, to_bytes(message))
TypeError: initializer for ctype 'git_signature *' must be a cdata pointer, not bytes
When I tried it with version 0.22.0 it didn't raise an error, but push operation also didn't work.
Note: I think the problem with signature parameter, because when I pass None It works fine with default signature .
Thanks.
I had updated pygit2 to v0.22.1, libgit2 to v0.22.3 , it fixed the problem.
I'm trying to launch AWS EMR cluster using boto library, everything works well.
Because of that I need to install required python libraries, tried to add bootstrap action step using boto.emr.bootstrap_action
But It gives error below;
Traceback (most recent call last):
File "run_on_emr_cluster.py", line 46, in <module>
steps=[step])
File "/usr/local/lib/python2.7/dist-packages/boto/emr/connection.py", line 552, in run_jobflow
bootstrap_action_args = [self._build_bootstrap_action_args(bootstrap_action) for bootstrap_action in bootstrap_actions]
File "/usr/local/lib/python2.7/dist-packages/boto/emr/connection.py", line 623, in _build_bootstrap_action_args
bootstrap_action_params['ScriptBootstrapAction.Path'] = bootstrap_action.path AttributeError: 'str' object has no attribute 'path'
Code below;
from boto.emr.connection import EmrConnection
conn = EmrConnection('...', '...')
from boto.emr.step import StreamingStep
step = StreamingStep(name='mapper1',
mapper='s3://xxx/mapper1.py',
reducer='s3://xxx/reducer1.py',
input='s3://xxx/input/',
output='s3://xxx/output/')
from boto.emr.bootstrap_action import BootstrapAction
bootstrap_action = BootstrapAction(name='install related packages',path="s3://xxx/bootstrap.sh", bootstrap_action_args=None)
job = conn.run_jobflow(name='emr_test',
log_uri='s3://xxx/logs',
master_instance_type='m1.small',
slave_instance_type='m1.small',
num_instances=1,
action_on_failure='TERMINATE_JOB_FLOW',
keep_alive=False,
bootstrap_actions='[bootstrap_action]',
steps=[step])
What's the proper way of passing bootstrap arguments?
You are passing the bootstrap_actions argument as a literal string rather than as a list containing the BootstrapAction object you just created. Try this:
job = conn.run_jobflow(name='emr_test',
log_uri='s3://xxx/logs',
master_instance_type='m1.small',
slave_instance_type='m1.small',
num_instances=1,
action_on_failure='TERMINATE_JOB_FLOW',
keep_alive=False,
bootstrap_actions=[bootstrap_action],
steps=[step])
Notice that the ``bootstrap_action` argument is different here.
I'm trying to automate the addition of new portgroups to ESXi hosts using pysphere. I'm using the following code fragment:
from pysphere import MORTypes
from pysphere import VIServer, VIProperty
from pysphere.resources import VimService_services as VI
s = VIServer()
s.connect(vcenter, user, password)
host_system = s.get_hosts().keys()[17]
prop = VIProperty(s, host_system)
propname = prop.configManager._obj.get_element_networkSystem()
vswitch = prop.configManager.networkSystem.networkInfo.vswitch[0]
network_system = VIMor(propname, MORTypes.HostServiceSystem)
def add_port_group(name, vlan_id, vswitch, network_system):
request = VI.AddPortGroupRequestMsg()
_this = request.new__this(network_system)
_this.set_attribute_type(network_system.get_attribute_type())
request.set_element__this(_this)
portgrp = request.new_portgrp()
portgrp.set_element_name(name)
portgrp.set_element_vlanId(vlan_id)
portgrp.set_element_vswitchName(vswitch)
portgrp.set_element_policy(portgrp.new_policy())
request.set_element_portgrp(portgrp)
s._proxy.AddPortGroup(request)
However, when I attempt to run it, I get the following error:
>>> add_port_group(name, vlan_id, vswitch, network_system)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 12, in add_port_group
File "/usr/lib/python2.6/site-packages/pysphere-0.1.8- py2.6.egg/pysphere/resources/VimService_services.py", line 4344, in AddPortGroup
response = self.binding.Receive(AddPortGroupResponseMsg.typecode)
File "/usr/lib/python2.6/site-packages/pysphere-0.1.8- py2.6.egg/pysphere/ZSI/client.py", line 545, in Receive
return _Binding.Receive(self, replytype, **kw)
File "/usr/lib/python2.6/site-packages/pysphere-0.1.8- py2.6.egg/pysphere/ZSI/client.py", line 464, in Receive
raise FaultException(msg)
pysphere.ZSI.FaultException: The object has already been deleted or has not been completely created
I've attempted to swap in different values for "vswitch" and "network_system", but I haven't had any success. Has anyone attempted to do something similar with pysphere successfully?
I can accomplish what I need through Powershell, which demonstrates that it isn't a vmware issue, but I don't want to use Powershell in this particular case.
I tried your code on one of our vSpheres.
It seems you are passing the object to set_element_vswitchName rather than the name. Maybe this will help:
vswitch = prop.configManager.networkSystem.networkInfo.vswitch[0].name