I'm a total newbie when it comes to servers, so this question my sound silly to you, but I stucked and I need you help once more.
I have written a simple server in python, which looks like this:
#!/usr/bin/env python
from socket import *
import time
s = socket(AF_INET, SOCK_STREAM)
s.bind(('', 8888))
s.listen(5)
while 1:
client,addr = s.accept()
print 'Connected to ', addr
client.send(time.ctime(time.time()))
client.close()
So when i write localhost:8888 in my browser, i get the message with the current server time.
The next thing i want to do, is to configure my server to allow opening various files from my computer i.e. html or text ones. So when I write in my browser localhost:8888/text.html, this file opens. Where do i start with that?
I should mention I'm using linux mint and don't want to use any existing framework. I want to fully understand how the servers are working and responding.
Try this:
Create a script named webserver.py
import SimpleHTTPServer
import SocketServer
PORT = 8888
Handler = SimpleHTTPServer.SimpleHTTPRequestHandler
httpd = SocketServer.TCPServer(("", PORT), Handler)
print "serving at port", PORT
httpd.serve_forever()
Create a file named text.html and place it on the same dir where your webserver.py script is.
Run python webserver.py
Navigate to http://localhost:8888/text.html
Related
I'm developing on a remote server which I login using ssh and develop using vi. I however need to send Terminal notification commands osascript -e "display notification {} {} {}" and such commands back to my local terminal so I can get sound/mac notifications on my system. How do I achieve this?
I know I can use import os; os.sytem('command') for the script on server to send terminal commands on the machine its running in i.e., the server itself, but is there a similar command to send commands back to my local ? Ideally, I need this to be done from the scripts itself- because I have multiple triggers for notifications to be done.
You need to use some sockets
On your server machine you need something like this:
import socket
IP = "0.0.0.0" # Your Local Machine IP
PORT = 5200 # Your Local Machine Listening Port
def send_message(msg):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((IP, PORT))
s.send(bytes(msg, 'UTF-8'))
data = s.recv(4096)
s.close()
print(data)
You can use the method where ever you need, the only argument it takes is msg, simply it's the command you need to send to your local machine
On your local machine this script should do what you need:
import socket
import os
IP = "0.0.0.0" # 0.0.0.0 Means every available IP to assign, but you need to use your external IP on the script that u will use on server
PORT = 5200 # The port you want to listen on
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((IP, PORT))
s.listen(1)
while True:
conn, addr = s.accept()
print("Command from {}".format(addr))
data = conn.recv(4096)
if not data: continue
if data == b'stop': break # This line just defines a word that will make your local machine stop listening.
print(data)
command = data.decode('UTF-8')
os.system(command)
conn.send(data)
conn.close()
You need to run The local machine script first
I am trying to setup a very simply sockets app. My server code is:
import socket
s = socket.socket()
host = socket.gethostname()
port = 1234
s.bind((host,port))
s.listen(5) #Here we wait for a client connection
while True:
c, addr = s.accept()
print "Got a connection from: ", addr
c.send("Thanks for connecting")
c.close()
I placed this file on my remote Linode server and run it using python server.py. I have checked that the port is open using nap:
PORT STATE SERVICE
22/tcp open ssh
80/tcp open http
1234/tcp open hotline
I now run the client.py on my local machine:
import socket # Import socket module
s = socket.socket() # Create a socket object
port = 1234 # Reserve a port for your service.
s.connect(("139.xxx.xx.xx", port))
print s.recv(1024)
s.close # Close the socket when done
However I am not getting any kind of activity or report of connection. Could someone give me some pointers to what I might have to do? Do I need to include the hostname in the IP address I specify in the client.py? Any help would be really appreciated!
I've just summarize our comments, so your problem is this:
When you trying to using the client program connect to the server via the Internet, not LAN.
You should configure the
port mapping on your router.
And however, you just need configure the
port mapping for your server machine.
After you did that, then you can use the client program connect to your server prigram.
I was trying to create a python socket server that could send and receive data, so I created a socket on the server using the code here:
import socket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind(('', 1208))
serversocket.listen(5)
(client,(ip,port)) = serversocket.accept()
Then I tried to create a sample connection from my machine by going to command prompt and typing
telnet www.filesendr.com 1208
However, the console simply replies with "Could not open connection to the host, on port 1208...Connection failed." I went back over my code but couldn't identify the problem. Any help would be greatly appreciated.
I think part of the problem is that after you accept the connection you don't do anything else. Once the accept happens, you get to the end of the script, python exits and closes all open file handles (including the socket you just opened). If you want to be able to talk to yourself through telnet, try something like this:
import socket
import select
import sys
port = 1208
listener = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
listener.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
listener.bind(('',port))
listener.listen(128)
newSock, addr = listener.accept()
while True:
r,w,e = select.select([newSock,sys.stdin],[],[])
if newSock in r:
data = newSock.recv(4096)
sys.stdout.write(data)
if sys.stdin in r:
newSock.send(sys.stdin.readline())
Currently doing an assignment in which we are programming sockets in python and thus creating a web server when the webserver.py code is executed.The code should then display HTTP headers and other information when you access a file(test.html)from the web server. Now my code works (or I'd like to believe so) and I have created a test.html file and the question goes on to say that I should place the test.html file in the same directory as the web server, where exactly is that on my local machine? I placed the test.html in the same folder as webserver.py in the python's root directory and proceeded to 127.0.0.1:1336/test.html to test my code but it doesn't work, where exactly on my machine is the webserver directory in which I should place test.html? Is it that I have to use wamp/xamp and place the test.html in there?
N.B 1336 is the port I specified in the code to connect to.
#import socket module
from socket import *
serverSocket = socket(AF_INET, SOCK_STREAM)
#Prepare a sever socket
serverPort = 1336
serverSocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
serverSocket.bind(('', serverPort)) #set up socket connection
serverSocket.listen(1) #tells the server to try a maximum of one connect request before ending connection
while True:
#Establish the connection
print 'Ready to serve...'
connectionSocket, addr = serverSocket.accept()
print 'connected to port',serverPort
try:
message = connectionSocket.recv(1024) #Makes it so that you can recieve message from client
filename = message.split()[1]
f = open(filename[1:])
outputdata = f.open(filename[1:])
#Send one HTTP header line into socket2
#Fill in start
connectionSocket.send('HTTP/1.0 200 OK\r\n')
#Send the content of the requested file to the client
for i in range(0, len(outputdata)):
connectionSocket.send(outputdata[i])
connectionSocket.close()
except IOError:
#Send response message for file not found
print '404 Error : File Not Found.'
#Close client socket
connectionSocket.close()
serverSocket.close()
First of all, you shouldn't use the socket module to make a HTTP server. I recommend using the http.ser ver module, and change the working directory to where the html files are. Lets say i had test.html in C:\User\Desktop.
An example:
from http.server import HTTPServer, CGIHTTPRequestHandler
import os
os.chdir("C:/User/Desktop")
address = ("", 1336)
httpserver = HTTPServer(address,, CGIHTTPRequestHandler)
httpserver.serve_forever()
Then you can access it by 127.0.0.1:1336/test.html
If this isn't the answer you are looking for, please add the webserver.py to the question.
I must preface this with a full disclaimer that i'm very early in my python development days
I've made a simple python program that waits for a socket connection to the local ip address over port 20000. When it gets a connection, it pops up a message alert using the win32api.
#tcpintercomserver.py
import socket
import sys
import win32api
ip = socket.gethostbyname(socket.gethostname())
#socket creation
sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#Binding
server_address = (ip, 20000)
sock.bind(server_address)
print server_address
#Listen
sock.listen(1)
while True:
# Wait for a connection
connection, client_address = sock.accept()
win32api.MessageBox(0,'MessageText','Titletext', 0x00001000)
# Close Connection
connection.close()
I also have a mated client program that simply connects to the socket. The script takes an argument of the host you're trying to reach (DNS name or ip address)
#tcpintercomcli.py
import socket
import sys
# Create a TCP/IP socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
# Connect the socket to the port where the server is listening
server_address = (sys.argv[1], 20000)
sock.connect(server_address)
This all runs fine as scripts. I then used CX_Freeze to turn them into executables. Both run just like they did when they were scripts.
Now i've taken the server script and connected it to a service with srvany.exe and use of the SC command in windows.
I set up the service using SC create "intercom" binPath= "C:\dist\srvany.exe"
Under the intercom service key in the registry, i've added the Parameter's key, and under there set Application to a string value c:\dist\tcpintercomserver.exe
I then perform a "net start intercom" and the service launches successfully, and the tcpintercomserver.exe is listed as a running process. However, when i run the tcpintercomcli.py or tcpintercomcli.exe, no alert comes up.
I'm baffled...is there something with the CX_Freeze process that may be messing this up?
Service process cannot show messagebox, they don't have access to UI, they usually run as SYSTEM user. if you are running from service, proper way of debugging and showing messages are using EventLog.
See:
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog%28VS.71%29.aspx
If you are on Windows Vista or later, your script is running headlong into Session 0 Isolation -- where GUI elements from a Windows service are not shown on an interactive user's desktop.
You will probably see your message box if you switch to session 0...