TypeError: a bytes-like object is required, not 'str' in Python script for Sniffing using Scapy - scapy

`from scapy.all import *
from scapy.layers import http
def mysniff(interface):
sniff(iface=interface,store=False,prn=sniffed_packets)
def sniffed_packets(packet):
if packet.haslayer(http.HTTPRequest):
print(packet[http.HTTPRequest].Host + packet[http.HTTPRequest].Path)
if packet.haslayer(Raw):
load = packet[Raw].load
keys = ["username", "password", "pass", "email"]
for key in keys:
if key in load:
print(`load.encode`())
break
my sniff("Intel(R) 82574L Gigabit Network Connection")`
Want it to Print the Keys from the load that match the keywords as described above in the code. Although its executing the code and printing as expected but when I do an http login it displays the below error instead of printing the 'username' and 'password'.
Pls guide me as I am new to Python and Scapy.
Getting below error :
`Traceback (most recent call last):
File "sniff_packets.py", line 21, in <module>
mysniff("Intel(R) 82574L Gigabit Network Connection")
File "sniff_packets.py", line 5, in mysniff
sniff(iface=interface,store=False,prn=sniffed_packets)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\scapy-2.5.0.dev15-py3.8.egg\scapy\sendrecv.py", line 1310, in sniff
sniffer._run(*args, **kwargs)
File "C:\Program Files (x86)\Python38-32\lib\site-packages\scapy-2.5.0.dev15-py3.8.egg\scapy\sendrecv.py", line 1253, in _run
session.on_packet_received(p)
` `File "C:\Program Files (x86)\Python38-32\lib\site-packages\scapy-2.5.0.dev15-py3.8.egg\scapy\sessions.py", line 109, in on_packet_received`
result = self. prn(pkt)`
File "sniff_packets.py", line 15, in sniffed_packets
if key in load:
`TypeError:` a bytes-like object is required, not 'str'``
```
`

Related

Converting Python3 List(with str argument) to Bytes

I am new to programming as well as python, i am trying use below code to sniff http packets.
I am getting below error, i know i can use .encode() method instead try converting that list to bytes store it in a variable.
just wanted to understand my list keywords can this be converted to bytes.
TypeError: 'str' object cannot be interpreted as an integ
My code
#!/bin/python3
import scapy.all as scapy
from scapy.layers import http
def sniff(interface):
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packets)
def process_sniffed_packets(packet):
if packet.haslayer(http.HTTPRequest):
if packet.haslayer(scapy.Raw):
load = (packet[scapy.Raw].load)
keywords = ["usr", "username", "uname", "pwd", "pass", "password"]
keyword_b = bytes(keywords)
for eachword in keyword_b:
if eachword in load:
print(load)
break
sniff(eth0)
Complete trace back
root#kali:~/python_course_zaid/Writing a Packet Sniffer# ./packet_sniffer.py
Traceback (most recent call last):
File "./packet_sniffer.py", line 24, in <module>
sniff("eth0")
File "./packet_sniffer.py", line 7, in sniff
scapy.sniff(iface=interface, store=False, prn=process_sniffed_packets)
File "/usr/lib/python3/dist-packages/scapy/sendrecv.py", line 972, in sniff
sniffer._run(*args, **kwargs)
File "/usr/lib/python3/dist-packages/scapy/sendrecv.py", line 925, in _run
session.on_packet_received(p)
File "/usr/lib/python3/dist-packages/scapy/sessions.py", line 47, in on_packet_received
result = self.prn(pkt)
File "./packet_sniffer.py", line 14, in process_sniffed_packets
keyword_b = bytes(keywords)
TypeError: 'str' object cannot be interpreted as an integer
i know below code works
keywords = ["usr", "username", "uname", "pwd", "pass", "password"]
for eachword in keywords:
if eachword.encode() in load:
print(load)
break

What should I infer from the error: AttributeError: 'str' object has no attribute 'setdefault'

I have a python repository, which tries to connect with a database available on web and collect the relevant data. Now when I run the repo from local machine, I get the desired database and hence the output.
However, when I run the same code from the Windows Server and tries to connect the same website(proxy), I am getting the above error.
I have installed/uninstalled the respective ODBC driver but no luck
Can anyone suggest me any method to get out of this?
(ssf) C:\Users\admin-prakuma3\data-model_1>python main.py
Traceback (most recent call last):
File "main.py", line 612, in <module>
salesforce_daily_extractors()
File "main.py", line 44, in salesforce_daily_extractors
'StartDate': 'StartDate'
File "C:\Users\admin-prakuma3\data-model_1\SalesforceExtractor.py", line 23, in __run__
fields = sg.getConnection(sg).__getattr__(sfdc_object).describe()['fields']
File "C:\Users\admin-prakuma3\data-model_1\SalesforceGateway.py", line 19, in getConnection
security_token='************', proxies="*******:8080")
File "C:\Users\admin-prakuma3\.conda\envs\ssf\lib\site-packages\simple_salesforce\api.py", line 146, in __init__
domain=self.domain)
File "C:\Users\admin-prakuma3\.conda\envs\ssf\lib\site-packages\simple_salesforce\login.py", line 168, in SalesforceLogin
proxies=proxies)
File "C:\Users\admin-prakuma3\.conda\envs\ssf\lib\site-packages\requests\sessions.py", line 535, in post
return self.request('POST', url, data=data, json=json, **kwargs)
File "C:\Users\admin-prakuma3\.conda\envs\ssf\lib\site-packages\requests\sessions.py", line 479, in request
prep.url, proxies, stream, verify, cert
File "C:\Users\admin-prakuma3\.conda\envs\ssf\lib\site-packages\requests\sessions.py", line 656, in merge_environment_settings
proxies.setdefault(k, v)
AttributeError: 'str' object has no attribute 'setdefault'

How to solve the error: TypeError: a bytes-like object is required, not 'str' with FLASK-MAIL?

In one of my FLASK projects, I use flask-mail to send emails. I tried to attach a log file to the mail but I receive an error: TypeError: a bytes-like object is required, not 'str'. Here is the complete error:
Exception in thread Thread-37:
Traceback (most recent call last):
File "/usr/lib/python3.7/threading.py", line 917, in _bootstrap_inner
self.run()
File "/usr/lib/python3.7/threading.py", line 865, in run
self._target(*self._args, **self._kwargs)
File "/home/Tobin/Documents/PYTHON-PROJECTS/FLASK CHAOS V1/app/email.py", line 7, in send_async_email
mail.send(msg)
File "/home/Tobin/.local/lib/python3.7/site-packages/flask_mail.py", line 492, in send
message.send(connection)
File "/home/Tobin/.local/lib/python3.7/site-packages/flask_mail.py", line 427, in send
connection.send(self)
File "/home/Tobin/.local/lib/python3.7/site-packages/flask_mail.py", line 190, in send
message.as_bytes() if PY3 else message.as_string(),
File "/home/Tobin/.local/lib/python3.7/site-packages/flask_mail.py", line 385, in as_bytes
return self._message().as_bytes()
File "/home/Tobin/.local/lib/python3.7/site-packages/flask_mail.py", line 349, in _message
f = MIMEBase(*attachment.content_type.split('/'))
TypeError: a bytes-like object is required, not 'str'
Here is my code:
from threading import Thread
from flask_mail import Message
from app import app, mail
def send_async_email(app, msg):
with app.app_context():
mail.send(msg)
def send_email(subject, sender, recipients, text_body):
msg = Message(subject, sender=sender, recipients=recipients)
msg.body = text_body
with app.open_resource("../logs/chaos.log") as fp:
msg.attach(b'../logs/chaos.log', fp.read())
Thread(target=send_async_email, args=(app, msg)).start()
I read in a previous post that it was not possible to open a file in binary mode and treat it as str. One solution would be to use a byte object (msg.attach(b'../logs/chaos.log', fp.read())). but that does not seem to solve my problem. apparently there is an essential notion that escapes me, so how to solve this bug?
You are supplying wrong arguments to msg.attach(). See the API for the correct parameters. The first argument should be a filename, second a content type, third the data. So the call should read something like this:
with app.open_resource("../logs/chaos.log") as fp:
msg.attach('chaos.log', 'text/plain', fp.read())

exchangelib get task from task queryset MIME conversion is not supported for this item

I am trying to access an object
through a queryset created with exchangelib however I get an error MIME CONVERSION IS NOT SUPPORTED FOR THIS ITEM, I don't know what it means. I have tried the same code with calendar items and I have no problem whatsoever. thanks
from exchangelib import Account, Credentials, DELEGATE
credentials = Credentials(username='BUREAU\\pepe', password='pepe')
pepe_account = Account(
primary_smtp_address='pepe#office.com',
credentials=credentials,
autodiscover=True,
access_type=DELEGATE)
tasks = pepe_account.tasks.filter()
print(tasks) -- Works
for task in tasks:
print(task)
The iteration fails, instead of print(task) I also tried pass and I get the same message.
Traceback (most recent call last):
File "test.py", line 13, in <module>
for task in tasks:
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/queryset.py", line 197, in __iter__
for val in result_formatter(self._query()):
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/queryset.py", line 272, in _as_items
for i in iterable:
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/account.py", line 393, in fetch
for i in GetItem(account=self).call(items=ids, additional_fields=additional_fields, shape=IdOnly):
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 456, in _pool_requests
for elem in elems:
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 283, in _get_elements_in_response
container_or_exc = self._get_element_container(message=msg, name=self.element_container_name)
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 256, in _get_element_container
self._raise_errors(code=response_code, text=msg_text, msg_xml=msg_xml)
File "/home/pepe/.local/lib/python3.5/site-packages/exchangelib/services.py", line 273, in _raise_errors
raise vars(errors)[code](text)
exchangelib.errors.ErrorUnsupportedMimeConversion: MIME conversion is not supported for this item type.

Cannot run bind() with ldap3 in python3

Below is my code to try and query my ldap server. However, for some reason, I cannot seem to make the bind command work to progress in my code. I continue to get the following message and am not sure what it means or how to fix it. I apologize about the error message formatting. I tried my best to make it as readable as possible.
Any help would be greatly appreciated!
>>> from ldap3 import Server, Connection, SUBTREE
>>> server = Server('<server_name>')
>>> conn = Connection(server, user='<username>', password='<password>')
>>> conn.open()
>>> conn.bind()
Traceback (most recent call last):
File "", line 1, in
File "/usr/lib/python3.5/site-packages/ldap3/core/connection.py", line 427, in bind
response = self.post_send_single_response(self.send('bindRequest', request, controls))
File "/usr/lib/python3.5/site-packages/ldap3/strategy/sync.py", line 122, in post_send_single_response
responses, result = self.get_response(message_id)
File "/usr/lib/python3.5/site-packages/ldap3/strategy/base.py", line 298, in get_response
responses = self._get_response(message_id)
File "/usr/lib/python3.5/site-packages/ldap3/strategy/sync.py", line 168, in _get_response
dict_response = self.decode_response(ldap_resp)
File "/usr/lib/python3.5/site-packages/ldap3/strategy/base.py", line 403, in decode_response
result = bind_response_to_dict(component)
File "/usr/lib/python3.5/site-packages/ldap3/operation/bind.py", line 119, in bind_response_to_dict
'saslCreds': bytes(response['serverSaslCreds']) if response['serverSaslCreds'] is not None else None}
File "/usr/lib/python3.5/site-packages/pyasn1/type/univ.py", line 984, in bytes
return bytes(self._value)
File "/usr/lib/python3.5/site-packages/pyasn1/type/base.py", line 164, in plug
raise error.PyAsn1Error('Uninitialized ASN.1 value ("%s" attribute looked up)' % name)
pyasn1.error.PyAsn1Error: Uninitialized ASN.1 value ("len" attribute looked up)

Resources