Python bind cmd.exe to port - python

How do I bind cmd.exe onto a port in Python? I want to do the same thing as
Netcats "-e" argument. So the equivilent in Netcat would be:
netcat -l -p 8080 -e cmd.exe
But I want to code it myself in Python, without using Netcat. So how is this
done? Are there any functions/modules that can do this? How can I convert the process (cmd.exe) and make it a server so it runs on a port?

Listen to a port
Read the input
Pipe it to cmd.exe
Send back the output

Something along the lines of this, except you would have to change it into running on Windows (this example runs fine on Linux):
#!/usr/bin/env python
import socket
import subprocess
s = socket.socket(socket.AF_INET)
s.setsockopt(socket.IPPROTO_IP, socket.SO_REUSEADDR, 1)
s.bind(("", 9999))
s.listen(1)
(conn, address) = s.accept()
p = subprocess.Popen(["/bin/bash"],
stdin=conn, stdout=conn, stderr=conn)
If you run this program, and then in another terminal use netcat to connect to port 9999, you'll have a bash shell to play with. Be careful not to let the whole internet get access to this port, that would give anyone instant shell access on your machine :-)

Related

How to run a server in python

How to run a server in python?
I already have tried:
python -m SimpleHTTPServer
python -m HTTPServer
but its says to me:
invalid syntax
Can someone help me?
Thanks!
You can use this command in cmd or terminal
python -m SimpleHTTPServer <port_number> # Python 2.x
Python 3.x
python3 -m http.server # Python 3x
By default, this will run the contents of the directory on a local web server, on port 8000. You can go to this server by going to the URL localhost:8000 in your web browser.
I have made a remote access program that uses the Socket module. If you want to copy the code, that's fine. EDIT: You will need to run it using a cmd file like this: "python (filename).py." After that, you will need to add the line "pause"
#SERVER
import os
import socket
s = socket.socket()
host = socket.gethostname()
port = 8080
s.bind((host, port))
print("Server started at: ", host)
s.listen(1)
conn,addr = s.accept()
print(addr, "connected")
#CLIENT
import os
import socket
s = socket.socket()
port = 8080
host = "YOUR DESKTOP ID" (Your server should say it. I.E. "Server started at: (Desktop-123456)")

Prometheus python client error Address already in use

I'm running a web app with address 127.0.0.1:5000 and am using the python client library for Prometheus. I use start_http_server(8000) from the example in their docs to expose the metrics on that port. The application runs, but I get [Errno 48] Address already in use and the localhost:8000 doesn't connect to anything when I try hitting it.
If I can't start two servers from one web app, then what port should I pass into start_http_server() in order to expose the metrics?
There is nothing already running on either port before I start the app.
Some other process is utilizing the port (8000). To kill the process that is running on the port (8000), simply find the process_id [pid] of the process.
lsof -i :8000
This will show you the processes running on the port 8000 like this:
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
python3 21271 hashed 3u IPv4 1430288 0t0 TCP *:8000 (LISTEN)
You can kill the process using the kill command like this:
sudo kill -9 21271
Recheck if the process is killed using the same command
lsof -i :8000
There should be nothing on the stdout.
When flask's debug mode is set to True, the code reloads after the flask server is up, and a bind to the prometheus server is been called a second time
Set flask app debug argument to False to solve it
This is mainly because you are restarting the server again on the port 8000.
To resolve this I created a function which will create the server after assuring the previous server or the port can be used.
You can look at https://github.com/prometheus/client_python/issues/155, here the same case is addressed
Port 8000 does not need to have a web server running on it for it to be already in use. Use your OS command line to find the process that is using up the port then kill it. If a service is also running that causes it to get spawned again, disable that process.
A simpler solution would be to use another port instead of 8000.
EDIT: Looks like it is a bug in Prometheus. Github Issue
you cannot run two http servers on the same thread.
I don't know why but the implementation of the prometheus_client doesn't runs the server on a separate thread.
my solution is
import logging.config
import os
import connexion
from multiprocessing.pool import ThreadPool
from prometheus_client import start_http_server
app = connexion.App(__name__, specification_dir='./')
app.add_api('swagger.yml')
# If we're running in stand alone mode, run the application
if __name__ == '__main__':
pool = ThreadPool(1)
pool.apply_async(start_http_server, (8000, )) # start prometheus in a different thread
app.run(host='0.0.0.0', port=5000, debug=True) . # start my server
Maybe your 8000 port is occupied. You can change it to another port, such as 8001

How to pass Unix Commands across network using python

So basically I have this remote computer with a bunch of files.
I want to run unix commands (such as ls or cat) and receive them locally.
Currently I have connected via python's sockets (I know the IP address of remote computer). But doing:
data = None
message = "ls\n"
sock.send(message)
while not data:
data = sock.recv(1024) <- stalls here forever
...
is not getting me anything.
There is an excellent Python library for this. It's called Paramiko: http://www.paramiko.org/
Paramiko is, among other things, an SSH client which lets you invoke programs on remote machines running sshd (which includes lots of standard servers).
You can use Python's subprocess module to accomplish your task. It is a built-in module and does not have much dependencies.
For your problem, I would suggest the Popen method, which runs command on remote computer and returns the result to your machine.
out = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE, stderr=subprocess.PIPE)
t = out.stdout.read() + out.stderr.read()
socket.send(t)
where cmd is your command which you want to execute.
This will return the result of the command to your screen.
Hope that helps !!!
This is what I did for your situation.
In terminal 1, I set up a remote shell over a socket using ncat, a nc variant:
$ ncat -l -v 50007 -e /bin/bash
In terminal 2, I connect to the socket with this Python code:
$ cat python-pass-unix-commands-socket.py
import socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(('', 50007))
sock.send('ls\n')
data = sock.recv(1024)
print data
sock.close()
$ python pass-unix-commands-socket.py
This is the output I get in terminal 1 after running the command:
Ncat: Version 6.40 ( http://nmap.org/ncat )
Ncat: Listening on :::50007
Ncat: Listening on 0.0.0.0:50007
Ncat: Connection from 127.0.0.1.
Ncat: Connection from 127.0.0.1:39507.
$
And in terminal 2:
$ python pass-unix-commands-socket.py
alternating-characters.in
alternating-characters.rkt
angry-children.in
angry-children.rkt
angry-professor.in
angry-professor.rkt
$

Port 8000, PID 4, not able to kill, taskill /f /pid 4, Access Denied

I am not able to kill process bound to 8000 port, due to which I am not able to start HTTP server. This is in reference to question
Start HTTP/HTTPS server, python -m SimpleHTTPServer
C:\>taskkill /f /pid 4
ERROR: The process with PID 4 could not be terminated.
Reason: Access is denied.
Even killing by below is not working which I found somewhere.
C:\>taskkill /f /s localhost /pid 4
ERROR: The process with PID 4 could not be terminated.
Reason: Access Denied.
PID 4 is system process, what might be running on there, how do I stop it, why are other ports is a similar fashion listening.
C:\>netstat -ab
Active Connections
Proto Local Address Foreign Address State
TCP 0.0.0.0:135 garg10may-PC:0 LISTENING
RpcSs
[svchost.exe]
TCP 0.0.0.0:443 garg10may-PC:0 LISTENING
[vmware-hostd.exe]
TCP 0.0.0.0:445 garg10may-PC:0 LISTENING
Can not obtain ownership information
TCP 0.0.0.0:902 garg10may-PC:0 LISTENING
[vmware-authd.exe]
TCP 0.0.0.0:912 garg10may-PC:0 LISTENING
[vmware-authd.exe]
TCP 0.0.0.0:8000 garg10may-PC:0 LISTENING
Can not obtain ownership information
if you're in Windows this might help you, the port 80 is usually being used by this service: "World Wide Web Publishing Service", open "Services" in the Control Panel and stop it
As per python documentation the http.server module can also be invoked directly using the -m switch of the interpreter with a port number argument. Similar to the previous example, this serves the files relative to the current directory.
python -m http.server 8000
In case your port 8000 is already is being used just change it to another no.
python -m http.server 5000
It's not a good idea to arbitrarily just kill processes and more over system processes.
Don't do this - there is a reason why you are not able to kill it, because you didn't start it. Instead pass another port number:
For Python 3:
python -m http.server 8080
For Python 2:
python -m SimpleHTTPServer 8080

How do I start python XMLRPC server in the background?

I wrote a python XMLRPC server for my web application. The problem is whenever I start the server from shell and exit, xmlrpc server stops as well. I tried executing server script from another file thinking that it will continue to run in the background but that didn't work. Here's the code used to start a server.
host = 'localhost'
port = 8000
server = SimpleXMLRPCServer.SimpleXMLRPCServer((host, port))
server.register_function(getList)
server.serve_forever()
In the shell I just do >>python MyXmlrpcServer.py to start a server.
What do I do to be able to start a server and keep it running?
#warwaruk makes a useful suggestion; Twisted XML-RPC is simple and robust. However, if you simply want to run and manage a python process in the 'background' take a look at Supervisord. It is a simple process management system.
$ pip install supervisor
$ echo_supervisord_conf > /etc/supervisord.conf
Edit that config file to add a definition of your process thus...
[program:mycoolproc]
directory=/path/to/my/script/dir
command=python MyXmlrpcServer.py
Start supervisord and start your process
$ supervisord
$ supervisorctl start mycoolproc
Better use twisted to create an XML-RPC server. Thus you will not need writing your own server, it is very flexible, and you will be able to run in background using twistd:
#!/usr/bin/env python
import time, datetime, os, sys
from twisted.web import xmlrpc, server
from twisted.internet import reactor
class Worker(xmlrpc.XMLRPC):
def xmlrpc_test(self):
print 'test called!'
port = 1235
r = Worker(allowNone=True)
if __name__ == '__main__':
print 'Listening on port', port
reactor.listenTCP(port, server.Site(r))
reactor.run()
else: # run the worker as a twistd service application: twistd -y xmlrpc_server.py --no_save
from twisted.application import service, internet
application = service.Application('xmlrpc_server')
reactor.listenTCP(port, server.Site(r))
reactor.run()
#internet.TCPServer(port, server.Site(r)).setServiceParent(application)

Categories