Posts: 1
Threads: 1
Joined: Nov 2017
Nov-09-2017, 05:39 PM
(This post was last modified: Nov-09-2017, 07:01 PM by Larz60+.)
I'm very new to learning Python and I'm trying to have a client send a text file to a server and have the server write it to another text file named "text.txt". I've kinda got it to work but the issue is that the only way the server writes it to the text file is if it exits. Also in order for the "text.txt" file to show me it's contents I have to click a "Reload" button. I just wanted to try and make it be a little more automated and without having to kill the server every time. I know this probably is really awful looking but like I said I am very new.
SERVER:
#!/usr/bin/env python3
# Echo server program
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))
tst = open('text.txt','w')
while(1):
s.listen(1)
# print type(s.accept())
conn, addr = s.accept()
print ('Connected by', addr)
while 1:
data = conn.recv(1024)
tst.write(data.decode())
if not data: break
conn.sendall(data)
if data: exit()
conn.close()
tst.close()
CLIENT:
#!/usr/bin/env python3
import socket
import sys
import subprocess
HOST = '172.19.40.52' # The target IP address
PORT = 50007 # The target port as used by the server
DATA = open('goodpasswd.txt','r')
BDATA = DATA.read().encode()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(BDATA) #Put the pattern you want to send here.
data = s.recv(1024)
s.close()
Posts: 606
Threads: 3
Joined: Nov 2016
Nov-10-2017, 06:15 AM
(This post was last modified: Nov-10-2017, 06:15 AM by heiner55.)
With some tiny changes, your code runs well.
Win7, Python 3.6.
Server and Client runs on same computer.
#!/usr/bin/env python3
# client
import socket
import sys
HOST = 'localhost' # The target IP address
PORT = 50007 # The target port as used by the server
DATA = open('good.txt','r')
BDATA = DATA.read().encode()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
s.send(BDATA) #Put the pattern you want to send here.
s.close() #!/usr/bin/env python3
# server
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))
cnt = 0
while(1):
s.listen(1)
# print type(s.accept())
conn, addr = s.accept()
print('Connected by', addr)
tst = open('text' + str(cnt)+ '.txt','w')
cnt = cnt + 1
while 1:
data = conn.recv(1024)
if data:
tst.write(data.decode())
else:
conn.close()
tst.close()
break
Posts: 4
Threads: 0
Joined: Feb 2019
Feb-24-2019, 03:10 PM
(This post was last modified: Feb-24-2019, 03:24 PM by buran.)
import socket
import sys
import os
import hashlib
HOST = 'localhost'
PORT = 8000
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print('Server Created')
except OSError as e:
print('Failed to create socket. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
try:
s.bind((HOST, PORT))
except OSError as e:
print('Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1])
sys.exit()
print('Socket bind complete')
s.listen(1)
print('Server now listening')
while (1):
conn, addr = s.accept()
print('Connected with ' + addr[0] + ':' + str(addr[1]))
reqCommand = conn.recv(1024)
print('Client> %s' % (reqCommand))
string = reqCommand
if (reqCommand == 'quit'):
break
elif (reqCommand == 'lls'):
toSend = ""
path = os.getcwd()
dirs = os.listdir(path)
for f in dirs:
toSend = toSend + f + ' '
conn.send(toSend)
# print path
elif (string[1] == 'shortlist'):
path = os.getcwd()
command = 'find ' + path + ' -type f -newermt ' + string[2] + ' ' + string[3] + ' ! -newermt ' + string[
4] + ' ' + string[5]
var = commands.getstatusoutput(command)
var1 = var[1]
var = var1.split('\n')
rslt = ""
for i in var:
comm = "ls -l " + i + " | awk '{print $9, $5, $6, $7, $8}'"
tup = commands.getstatusoutput(comm)
tup1 = tup[1]
str = tup1.split(' ')
str1 = str[0]
str2 = str1.split('/')
rslt = rslt + str2[-1] + ' ' + str[1] + ' ' + str[2] + ' ' + str[3] + ' ' + str[4] + '\n'
conn.send(rslt)
elif (string[1] == 'longlist'):
path = os.getcwd()
var = commands.getstatusoutput("ls -l " + path + " | awk '{print $9, $5, $6, $7, $8}'")
var1 = ""
var1 = var1 + '' + var[1]
conn.send(var1)
elif (string[0] == 'FileHash'):
if (string[1] == 'verify'):
BLOCKSIZE = 65536
hasher = hashlib.sha1()
with open(string[2], 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
conn.send(hasher.hexdigest())
print('Hash Successful')
elif (string[1] == 'checkall'):
BLOCKSIZE = 65536
hasher = hashlib.sha1()
path = os.getcwd()
dirs = os.listdir(path)
for f in dirs:
conn.send(f)
with open(f, 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
conn.send(hasher.hexdigest())
print('Hash Successful')
else:
string = reqCommand.split(' ') # in case of 'put' and 'get' method
if (len(string) > 1):
reqFile = string[1]
if (string[0] == 'FileUpload'):
file_to_write = open(reqFile, 'wb')
si = string[2:]
for p in si:
p = p + " "
print("User" + p)
file_to_write.write(p)
while True:
data = conn.recv(1024)
print("User" + data)
if not data:
break
file_to_write.write(data)
file_to_write.close()
print('Receive Successful')
elif (string[0] == 'FileDownload'):
with open(reqFile, 'rb') as file_to_send:
for data in file_to_send:
conn.sendall
print('Send Successful')
conn.close()
s.close()
import socket
import sys
import os
import hashlib
HOST = 'localhost' # server name goes in here
PORT = 8000
def put(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
string = commandName.split(' ', 1).encode()
inputFile = string.encode()
socket1.send(commandName)
with open(inputFile, 'rb') as file_to_send:
for data in file_to_send:
socket1.sendall(data)
print("Client users " + data)
socket1.send(data)
print('Upload Successful')
socket1.close()
return
def get(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ')
inputFile = string[1]
with open(inputFile, 'wb') as file_to_write:
while True:
data = socket1.recv(1024)
if not data:
break
# print data
file_to_write.write(data)
file_to_write.close()
print('Download Successful')
socket1.close()
return
def FileHash(commandName):
string = commandName.split(' ')
if string[1] == 'verify':
verify(commandName)
elif string[1] == 'checkall':
checkall(commandName)
def verify(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
hashValServer = socket1.recv(1024)
string = commandName.split(' ')
BLOCKSIZE = 65536
hasher = hashlib.sha1()
with open(string[2], 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
hashValClient = hasher.hexdigest()
print('hashValServer= %s', (hashValServer))
print('hashValClient= %s', (hashValClient))
if hashValClient == hashValServer:
print('No updates')
else:
print('Update Available')
socket1.close()
return
def checkall(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
string = commandName.split(' ')
BLOCKSIZE = 65536
hasher = hashlib.sha1()
# f=socket1.recv(1024)
while True:
f = socket1.recv(1024)
with open(f, 'rb') as afile:
buf = afile.read(BLOCKSIZE)
while len(buf) > 0:
hasher.update(buf)
buf = afile.read(BLOCKSIZE)
hashValClient = hasher.hexdigest()
hashValServer = socket1.recv(1024)
print('Filename = %s', f)
print('hashValServer= %s', (hashValServer))
print('hashValClient= %s', (hashValClient))
if hashValClient == hashValServer:
print('No updates')
else:
print('Update Available')
if not f:
break
socket1.close()
return
def quit():
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
socket1.close()
return
def IndexGet(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
string = commandName.encode('utf-8').split(' ')
if string[1] == 'shortlist':
socket1.send(commandName)
strng = socket1.recv(1024)
strng = strng.split('\n')
for f in strng:
print(f)
elif (string[1] == 'longlist'):
socket1.send(commandName)
path = socket1.recv(1024)
rslt = path.split('\n')
for f in rslt[1:]:
print(f)
socket1.close()
return
def serverList(commandName):
socket1 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socket1.connect((HOST, PORT))
socket1.send(commandName)
fileStr = socket1.recv(1024)
fileList = fileStr.split(' ', 1)
for f in fileList[:-1]:
print(f)
socket1.close()
return
msg = input('Enter your name: ')
while (1):
print("\n")
print("****************")
print('Instruction')
print('"FileUpload [filename]" to send the file the server ')
print('"FileDownload [filename]" to download the file from the server ')
print('"ls" to list all files in this directory')
print('"lls" to list all files in the server')
print('"IndexGet shortlist <starttimestamp> <endtimestamp>" to list the files modified in mentioned timestamp.')
print('"IndexGet longlist" similar to shortlist but with complete file listing')
print('"FileHash verify <filename>" checksum of the modification of the mentioned file.')
print('"quit" to exit')
print("\n")
sys.stdout.write('%s> ' % msg)
inputCommand = sys.stdin.readline().strip()
if (inputCommand == 'quit'):
quit()
break
elif (inputCommand == 'ls'):
path = os.getcwd()
dirs = os.listdir(path)
for f in dirs:
print(f)
elif (inputCommand == 'lls'):
serverList('lls')
else:
string = inputCommand.split(' ', 1)
if string[0] == 'FileDownload':
get(inputCommand)
elif string[0] == 'FileUpload':
put(inputCommand)
elif string[0] == 'IndexGet':
IndexGet(inputCommand)
elif string[0] == 'FileHash':
FileHash(inputCommand)
Posts: 4
Threads: 0
Joined: Feb 2019
Feb-24-2019, 04:54 PM
(This post was last modified: Feb-24-2019, 07:26 PM by buran.)
I keep getting this error "byte like object not str'. how do i fix it.
Posts: 4
Threads: 0
Joined: Feb 2019
server.py
Server Created
Socket bind complete
Server now listening
Connected with 127.0.0.1:51150
Client> b''
Traceback (most recent call last):
File "./server.py", line 34, in <module>
string = reqCommand.split(' ')
TypeError: a bytes-like object is required, not 'str'
client.py
Instruction
"FileUpload [filename]" to send the file the server
"FileDownload [filename]" to download the file from the server
"ls" to list all files in this directory
"lls" to list all files in the server
"IndexGet shortlist <starttimestamp> <endtimestamp>" to list the files modified in mentioned timestamp.
"IndexGet longlist" similar to shortlist but with complete file listing
"FileHash verify <filename>" checksum of the modification of the mentioned file.
"quit" to exit
lls
h> Traceback (most recent call last):
File "./client.py", line 185, in <module>
serverList('lls')
File "./client.py", line 150, in serverList
socket1.send(commandName)
TypeError: a bytes-like object is required, not 'str'
This are the errors from both codes.
Posts: 4
Threads: 0
Joined: Feb 2019
This is the error i got from the terminal.
server.py
Server Created
Socket bind complete
Server now listening
Connected with 127.0.0.1:51150
Client> b''
Traceback (most recent call last):
File "./server.py", line 34, in <module>
string = reqCommand.split(' ')
TypeError: a bytes-like object is required, not 'str'
client.py
Instruction
"FileUpload [filename]" to send the file the server
"FileDownload [filename]" to download the file from the server
"ls" to list all files in this directory
"lls" to list all files in the server
"IndexGet shortlist <starttimestamp> <endtimestamp>" to list the files modified in mentioned timestamp.
"IndexGet longlist" similar to shortlist but with complete file listing
"FileHash verify <filename>" checksum of the modification of the mentioned file.
"quit" to exit
lls
h> Traceback (most recent call last):
File "./client.py", line 185, in <module>
serverList('lls')
File "./client.py", line 150, in serverList
socket1.send(commandName)
TypeError: a bytes-like object is required, not 'str'
This are the errors from both codes.
|