Python SSH Interactive Shell call back on data receive - python

I'm trying to implement a interactive SSH shell using python as back-end. Basically I want to pass each character to shell along with and special character like new line, Ctrl-C. Then pass back the result. I found similar solution in node.js at Connecting to remote SSH server (via Node.js/html5 console)
I can establish a websocket from fronend/JS side and send each character on key-press. But I'm facing problem in getting shell output back. In node.js ssh2 package its looks like on receiving data it can call some function
}).on('data', function(data) {
console.log('STDOUT: ' + data);
}).stderr.on('data', function(data) {
console.log('STDERR: ' + data);
});
I checked the python's ssh2-python and Paramiko, but in both I see we have to loop continuously and check if any data is available on channel. Do we have something like callback similar to node.js ?
So that I can handle incoming stream + continuous outgoing stream( in case of command like top and ping)

Related

Start python script with information containing message directly from messenger API in a safe way

My network configuration: I have a revers proxy nginx handling https behind it will be a golang server (gs).
I want gs to run my python script with the data that comes in as JSON with the POST at /webhook.
I Thought about using sys.args but I am not sure is it, or how to make it safe. Is there an injection attack possible?
My plan was to make gs parse the JSON and run:
python3 respond.py -txt "this is message sent from messenger" -mid 0000000000 -pld "payload if a button was pressed"
Python would create message and sent it to facebook by it self, so it would have to be called for every messsage. The traffic isn't big but still if there is a best solution I would like to find it.
Other thing that I considered was to run python3 listening on a port and forward to it raw incoming JSON over tcp (JSON that golang server recieves).
Does the Script have to run often or only with some requests?
If yes, consider implementing a pipe between the processes and have the python script listen for incomming messages via the pipe.

How to correctly configure and close an SSH session with paramiko

I have an Onion Omega2 device acting as a linux server that has a UART stream from an Arduino chip. Through the terminal on my laptop I can connect via SSH and stream the data from the UART coming into the device. I then attempted to create an SSH shell in Python using Paramiko. Code shown below:
import paramiko
def ssh_comm(ip, usr, passwd):
client = paramiko.SSHClient();
client.set_missing_host_key_policy(paramiko.AutoAddPolicy());
client.connect(ip, username=usr, password=passwd);
channel = client.invoke_shell();
channel.send("screen /dev/ttyS1 9600 \n");
print("/n");
points = 0;
while points < 100:
if channel.recv_ready():
print(channel.recv(1024));
points = points + 1;
channel.shutdown(2);
client.close();
return;
ssh_comm("192.xxx.x.x", "root", "password");
First time around it connects well and all data is streamed back to my laptop. However when I let the shell close and then re-open it I only recieve a few packets every now and then back from the Omega2. (It still connects fine though) After connecting through python the transmission is also intermittent when forming the SSH connection on the terminal using: ssh root#192.xxx.x.x.
Restarting the Omega 2 fixes this however since I can repeatedly connect though the terminal with no issues I beleive the problem must be to do with closing the session within the python code. Or not configuring it properly. Having looked through the paramiko docs and tried my best to configure it correctly I still get the same issue. Any ideas as to what could be causing it?
I found that the error is not to do with the SSH configuration but rather not closing the screen command before closing the channel. this was done by sending CTRL-A then k then y.
channel.send("\x01");
channel.send("k");
channel.send("y");
The \x01 represents CTRL-A. Without this re-running the program causes a second screen to be created and they both fight over the UART stream. Solution was found with reference to: Python Paramiko send CTRL+C to an ssh shell And provides a second method of fixing the problem.

Streaming responses between node js server and python

i need an advice over how to set up streaming responses from node js server to python, from python back to node js.
There are four files
a) The node js script
b) The serverConn.py script
c) The python file that takes input from serverconn.py script called count.py
d) the python file that takes input from count.py and return it back to serverConn to be sent back to the node.js server
I read up on zerorpc and i am currently using it to send input from the node js to python, but the python script also has to send the input to another python script, and that python script also has to send the input to another python script and then send the result back to the node js server.
Everything seems complicated for someone who just got out of college lol.
I saw this thread and was also wondering if i could use something like this for the two python scripts to communicate with each other.
How to get a python script to listen for inputs from another script
This is my node js script
var server = new zerorpc.Server({
hello: function(name, reply) {
var catalog = "3D";
reply(null, catalog + name);
}
});
server.bind("tcp://0.0.0.0:4244");
And this is my python script
import zerorpc
class serverConn:
def __init__(self):
self.c = "tcp://127.0.0.1:4244"
def client(self):
c = zerorpc.Client()
c.connect(self.c)
catalog = c.hello("")
return catalog
s = serverConn()
s.client()
The python script gets the input from the node js file, and sends it to matchcount.py file, and matchcount.py sends it to calculate.py file, and calculate.py file sends it back to node js.
Is there any tips on how i can go about this, and will the link i posted help?
Thank you.
Ok so you have nodejs -> python #1 -> python #2 -> python #3. The nodejs process is a client only. Python #1 and #2 are servers and clients to the next python process. Python #3 is a server only.
Thus your nodejs process should use a zerorpc client to invoke a given procedure on python #1. Python #1 will run a zerorpc Server with the procedure. In turn this procedure will use a zerorpc client and so on. When the last process returns from it's procedure, zerorpc will return the value back to the caller process. If each of your procedure always return the result of the remote procedure call. The result will eventually come back to the nodejs process.

Python paramiko SSH nothing returned when blocked by dialog

I'm using paramiko to ssh into a server and then from this server ssh into another one just to get the fingerprint, so I'd like to see the message that asks if I want to accept that fingerprint or no.
I'm using this code:
stdin,stdout,stderr = self.ssh.exec_command(command)
outlines = stdout.readlines()
resp = ''.join(outlines)
return resp
but it returns me nothing. I think it's because at some point the ssh command wait for me to input yes/no if I want to accept the fingerprint. I did man ssh and didn't find a way to automatically answer no for this question.
I've found this: Reading output of Top command using Paramiko which teaches how to invoke a shell. But what if I want to receive the text just up to the stopping point?

How to write commands to a serial port using NodeJs?

Good day everyone,
I am having issues writing commands to a lock connected to a USB controller which is connected to the laptop port using NodeJs. I have successfully achieved this in python, but is having issues in nodejs.
The reason why I am converting to nodejs is because the entire application is written in nodejs and runs has a desktop app via electron, and opening/closing port is just a small component of it.
The python equivalent and which works fine
ser = serial.Serial()
ser.baudrate = 38400 #Suggested rate in Southco documentation, both locks and program MUST be at same rate
// COMPORT is a variable that stores an integer such as 6
ser.port = "COM{}".format(COMPORT)
ser.timeout = 10
ser.open()
command = "open1"
#call the serial_connection() function
ser.write(("%s\r\n"%command).encode('ascii')) #Southco locks receives and sends commands in ASCII
Now in NodeJs, I am using the library serialport and I am trying to achieve this via nodejs that runs under the electron app.
var SerialPort = require('serialport');
var port = new SerialPort("COM6", {
baudRate: 38400
});
port.on('open', function() {
port.write(Buffer.from('open1', 'ascii'), function(err) {
if (err)
return sendData(500, err.message);
console.log('message written');
});
});
I know nodejs is able to interact with the port because when I run serialport-list in command prompt or when i run it within the code
SerialPort.list(function (err, ports) {
ports.forEach(function(port) {
console.log(port.comName, port.pnpId, port.manufacturer); // or console.log(port)
});
});
it shows the port information. Hence, nodejs is able to read the port, and issue information about the specific port, but I cant seem to issue command succesfully to it. It seems to get execute since no error message is thrown and it does display message written in console, but the lock does not react, whereas with the python code the lock does react by opening or closing demanding on the command that is written.
Any help would be appreciated.
If you look in the SerialPort docs you'll see that the port is immediately opened when a new instance is instantiated, unless you pass the option AutoOn=false.
So, in your case, the port is already open by the time you set the listener .on('open'), so it never receives an event. Remove the listener and just call .write() immediately.

Categories

Resources