i tried to do client and server and look what i do
#Server
import socket
Host=''
Port=305
OK=socket.socket()
OK.bind((Host,Port))
OK.listn(1)
OK.accept()
and another one for client
#Client
impot socket
Host='192.168.1.4'
Port=305
OK=socket.socket()
OK.connect((Host,Port))
First thing : for now every thing is ok but i want when client connect to server :
server print "Hello Admin" in client screen
second thing : i want make like input command ! like
COM=raw_input('enter you command system:')
then client enter dir for example then server print the result in client screen
Look here, this is a simple echo server written in Python.
http://ilab.cs.byu.edu/python/socket/echoserver.html
When you create a connection, the story isn't over. Now it's time to send data over the connection. Create a simple "protocol" (*) and use it to transfer data from client to server and/or back. One simple example is a textual protocol of commands separated by newlines - this is similar to what HTTP does.
(*) Protocol: an agreement between two parties on the format of their communication.
I think you might want to do something like this:
client, addr = OK.accept()
client.send("Hello Admin")
And then use
data = client.recv(1024)
to get data from the client.
If you want to get command input from the client, you just need to execute the commands the client sends and send the output back back to the client.
from commands import getoutput
client.send(getoutput(client.recv(1024)))
Thats about the easiest solution possible.
For Client:
import os
import sys
impot socket
Host=raw_input ("Please enter ip : ")
Port=raw_input ("please Enter port :")
OK=socket.socket()
OK.connect((Host,Port))
print " Enter Command")
cmd = raw_input()
os.system(cmd)
I think that your codes has an issue:
you seem to have OK = socket.socket(), but I think it should be:
OK = socket.socket(socket.AF_INET, socket.STREAM), which would help if your making a connection. And your server has a problem: OK.listn(1) should be OK.listen(1). And, don't forget about send() and recv().
#Client
import socket
Host='192.168.1.4'
Port=305
OK=socket.socket(socket.AF_INET, socket.STREAM)
OK.connect((Host,Port))
while True:
com = raw_input("Enter your command: ")
OK.send(com)
data = OK.recv(5000) #Change the buffer if you need to, I have it setup to run 5000
print "Received:\n" + data
which should work for the client
#Server
import socket
import os
Host=''
Port=305
OK=socket.socket(socket.AF_INET, socket.STREAM)
OK.bind((Host,Port))
OK.listen(1)
conn, addr = OK.accept()
while True:
data = conn.recv(2048) #Change the buffer if needed
if data == "":
break
r = os.system(data)
conn.send(str(r)) #Note this will send 0 or 1, 0 = ran, 1 = error
Note: These fixes would work for Windows, I don't know about Unix systems.*
Related
I'm trying to build a very simple TELNET client in Python and I'm getting problem on the last part: sending/receiving data to/from the server.
With the code I have, if no data arrives at the very beginnig, the loop get paused and I can't even send commands.
Here the interested part of the code:
# Infinite cycle that allows user to get and send data from/to the host
while True:
incoming_data = my_socket.recv(4096)
if not incoming_data:
print('Problem occurred - Connection closed')
my_socket.close()
sys.exit()
else:
# display data sent from the host trough the stdout
sys.stdout.write(incoming_data)
# Commands sent to the host
command = sys.stdin.readline()
my_socket.send(command)
(I think the program kinda of works if I try to connect to some hosts that send data at the beginning.)
The idea would be have two loops, running at the same time, getting data or sending data, but I can't get it to work.
I can't use the telnet library and I don't want to use the select library (only sys and socket).
You want to use the threading library.
The following program runs the receiving in one thread and the sending in another:
import socket
from threading import Thread
def listen(conn):
while True:
received = conn.recv(1024).decode()
print("Message received: " + received)
def send(conn):
while True:
to_send = input("Input message to send: ").encode()
conn.sendall(to_send)
host = "127.0.0.1"
port = 12345
sock = socket.socket()
sock.connect((host, port))
Thread(target=listen, args=[sock]).start()
Thread(target=send, args=[sock]).start()
This program is for Python 3. Python 2 is very similar, except print() works differently, and you don't need to encode() and decode() everything being sent through a socket.
The listen and send functions are run in parallel, so that as soon as data arrives, it is printed, but you can also send data at any time. Practically, you would probably want to make some changes so that the data isn't just printed over the input prompt. However, this would be hard just in a command line application.
Research queues for control over data passing between threads.
Let me know if you have any more questions.
I made a python socket server recently that listens on port 9777 the server is suppose to accept connections and once it does will allow you to send information to the client. The client will then print out whatever it received. However, I found that after I sent some data the server would hang until i reinitialized a new connection. Is there a reason for this and if so how can I prevent it from happening
The code of the server is :
import socket
import sys
host='0.0.0.0'
port=9777
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((host,port))
s.listen(10)
c,a=s.accept()
while True:
command=raw_input('[input>] ')
if 'data' in command:
c.send('continue')
data=c.recv(1024)
print data
else:
continue
the code will only send data if the word data is in the string. Here is the code for the client:
import socket
import sys
host='192.168.0.13'
port=9777
while True:
try:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.connect((host,port))
except:
continue
while True:
d=s.recv(9999)
print d
s.send('received')
My goal is to setup a connection between server and client. I want the server to be able to accept input from a user in a while loop and send the input to the client. The client needs to be able to receive information and when it does it will send a response to the server. Then the user can continue sending data to the server until they decide to terminate the program. However the server keeps hanging after sending data once to the client. Can anyone tell me how I can prevent that?
I try this code in my computer it's work fine , maybe you need to change host='192.168.0.13' to host='localhost'
and host='0.0.0.0' to host='localhost'
look at this picture
and if this problem stay maybe your ip address is the same of other device in the network for that try to run this command ipconfig /renew
I am trying to test socket communication on my laptop using python. However, I'm not sure why the connection is not being established? I keep getting error that the target machine is actively refusing connection. I am trying to use the same computer to run both the client and the server portion. The server is running fine but the client is the one not connecting. I think I have the hostname wrong (127.0.0.1) but not sure what Im supposed to be using? I also tried changing the server hostname to (0.0.0.0) and the IPV4 address for the hostname the client was to connect to but that didn't work either. Any help would be appreciated!
My code(server portion):
import socket
comms_socket =socket.socket()
comms_socket.bind(('127.0.0.1', 50000))
comms_socket.listen(10)
connection, address = comms_socket.accept()
while True:
print(connection.recv(4096).decode("UTF-8"))
send_data = input("Reply: ")
connection.send(bytes(send_data, "UTF-8"))
Client portion:
import socket
comms_socket = socket.socket()
comms_socket.connect(('127.0.0.1',50000))
while True:
send_data = input("Message: ")
comms_socket.send(bytes(send_data, "UTF-8"))
print(comms_socket.recv(4096).decode("UTF-8"))
Your code won't work with python 2.* , because of the differences in input(), raw_input(), bytes, etc. in python 3.* vs python 2.* . You'd have to minimally make the following changes to get it working with python 2.*. Otherwise, use python 3 to run your code:
Server program:
import socket
comms_socket =socket.socket()
comms_socket.bind(('127.0.0.1', 7000))
comms_socket.listen(10)
connection, address = comms_socket.accept()
while True:
print(connection.recv(4096).decode("UTF-8"))
send_data = raw_input("Reply: ") # Use raw_input() instead of input()
connection.send(send_data.encode("UTF-8"))
Client program:
import socket
comms_socket = socket.socket()
comms_socket.connect(('127.0.0.1',7000))
while True:
send_data = raw_input("Message: ")
comms_socket.send(send_data.encode("UTF-8"))
print(comms_socket.recv(4096).decode("UTF-8"))
If you want to use bytes as intended in your specific usecase, you should use bytesarray instead in python 2.6 or higher. Check this: the bytes type in python 2.7 and PEP-358
I am trying to connect to a server using python sockets. I am able to make a connection and fetch the response data. However, I want the socket communication to be interactive from the client side.
For instance, if I use netcat to connect to the server, the communication is interactive:
nc aa.bb.cc.dd 1234
Server greets you
I can enter the input here
Server responds to my input
However, when I make the connection using python sockets, all I receive is the greeting from the Server and program completes execution.
Here is the python code I am using:
#! /usr/bin/python
import os
import sys
import socket
host = "aa.bb.cc.dd"
port = 1234
remote_ip = socket.gethostbyname(host)
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((remote_ip, port))
print s.recv(1024)
I want to modify the above python program so that I can send inputs to the Server as well.
Thanks.
Usually you do
input_data = input("Enter something: ")
s.send(bytes(input_data,'utf-8'))
You could use a while loop to get user input, send to server, and get a response continuously.
while True:
print(str(s.receive(1024)))
toSend = input()
s.send(bytes(toSend, "utf-8"))
I'm trying to make a proof of concept tcp server and client with Python 3.4. Everything with network part works nice. I tried to make it interactive and get user input from the client and send it to the server. But when I try to use it as HTTP client (write a custom request in console and send it to the server) it failed to get a response. The problem is that input() function interprets \r\n\ as string. How can I tell to python to interpret them as a .
Example :
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect(("www.google.com", 80))
user_input = input("Inser message: ") # GET / HTTP/1.1\r\n\r\n
sock.sendall(user_input.encode("utf-8"))
message = sock.recv(4096)
Thanks in advance for any suggestion.
You can use replace:
user_input = user_input.replace('\\r', '\r').replace('\\n', '\n')