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)")
Related
I want client socket can enter the server socket via localhost:8080,
but I keep getting this error message
:
ConnectionRefusedError: [Errno 111] Connection refused
This is my server socket
import socket
import threading
serverSocket = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
serverPort = 8080
serverSocket.bind(('', serverPort))
serverSocket.listen(1)
connectionSocket, address = serverSocket.accept()
print('*****',str(address), 'has entered.*****')
and Dockerfile
FROM python:3.7.4-alpine3.10
WORKDIR /app
COPY . /app
CMD ["python", "serversocket.py"]
EXPOSE 8080
This is client socket
import socket
import threading
clientSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serverPort = 8080
clientSocket.connect(('localhost', serverPort))
print('*****You Enter the server.*****')
and Dockerfile
FROM python:3.7.4-alpine3.10
WORKDIR /app
COPY . /app
CMD ["python", "clientsocket.py"]
and finally is my docker-compose.yml file
version: "3"
services:
server:
image: server
ports:
- "8080:8080"
client:
image: client
How can I solve this problem?
Your server and your client run in a Docker network. The fact that you open the server port 8080 is only relevant for your local machine.
In the context of the client container, localhost is not your local machine, it's its own "local network". So, trying to connect to localhost:8080 won't work from the local container.
What's nice with docker-compose is that it implicitly creates a common Docker network and bind it to each containers defined. Thus, inside a container, you can reach its fellow containers by their name.
You can try it if you run a shell session from inside the container:
docker-compose exec client sh # Opens a prompt INSIDE the client container
ping server # Ping the hostname server. It will respond.
So, let's go back to your issue. You should do this in your client code:
# The hostname is the name of the container, "server"
clientSocket.connect(('server', serverPort))
As a side note, it would be better if the server hostname and the port are defined as environment variables. It will allow you to easily change those values (for example, in the docker-compose file) without having to rebuild the image.
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
$
I communicate Python with Matlab via sockets. However, even before going there, I want to test sockets with netcat. So I establish server using nc -lkp 25771, and make Python client to send a message to this server:
import socket
host = 'localhost'
port = 25771
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((host,port))
s.send('Hello there')
s.close()
After running python client.py server prints out 'Hello there'; however, after I try to run client script one more time it raises exception.
Traceback (most recent call last):
File "client.py", line 13, in
s.connect((host,port))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
Why the same command raises the error second time? What changes after my first command?
You are using traditional version of netcat (netcat-traditional) which doesn't support -k option. you can confirm checking the man page of your netcat by typing man nc in your terminal .
Install the netcat-openbsd version using the command
sudo apt-get install netcat-openbsd
now switch to netcat-openbsd version using the command
sudo update-alternatives --config nc
and choose the netcat-openbsd .
now you can use nc -lk 25771 .
this listens on port 25771 for multiple connections .
you can also use the commands discussed here
Netcat: using nc -l port_number instead of nc -l -p port_number
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)
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 :-)