Attribute Error : "timer" object has no attribute "download" - python

I am doing a C/S project in which one of the function is a downloading file from the server.
The client is written in python and the server is written in java.
-f filename is a command that fetches the file.
The only problem is in the
def download(self,filename):
print "Start download file"
self.sock.send("DOWNLOAD"+"sprt"+filename)
downloadData = self.sock.recv();
print downloadData
and
if message[0:message.find(" ")] == "-f":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage -f filename\n"
else:
client.download(message[message.find(" ")+1:])
part.
AttributeError: 'timer' object has not attribute 'download'.
In contrast the
def upload(self,filename):
print "server ready , now client sending file~~"
try:
f = open(filename,'rb')
while (True):
data = f.read();
#if file is none
if data is None:
break;
#Notify the java server that a file is going to be sent.
#sprt stands for seperator
self.sock.sendall("FILE"+"sprt"+filename+"sprt"+data+'\n')
break;
f.close();
time.sleep(1)
#Notify the java server that the file is complete
self.sock.send("EOF\n")
print "send file success!"
except IOError:
print "No such file or Directory"
the method works normally.
What might cause the problem ? Thanks
Here is the whole file.
import threading
import sys
import time
import socket
class timer(threading.Thread):
def __init__(self):
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.sock.connect(('localhost', 9991))
self.isrun = True
threading.Thread.__init__(self);
def run(self):
while self.isrun:
revice = self.sock.recv(1024);
print ("recv> " + revice);
self.sock.close()
def send(self,str):
self.sock.send(str + "\n")
def close(self):
self.isrun=False
def upload(self,filename):
print "server ready , now client sending file~~"
try:
f = open(filename,'rb')
while (True):
data = f.read();
#if file is none
if data is None:
break;
#Notify the java server that a file is going to be sent.
#sprt stands for seperator
self.sock.sendall("FILE"+"sprt"+filename+"sprt"+data+'\n')
break;
f.close();
time.sleep(1)
#Notify the java server that the file is complete
self.sock.send("EOF\n")
print "send file success!"
except IOError:
print "No such file or Directory"
def download(self,filename):
print "Start download file"
self.sock.send("DOWNLOAD"+"sprt"+filename)
downloadData = self.sock.recv();
print downloadData
def main():
client = timer()
client.start()
print "Welcome:\n","Command to be used:\n","-a filename\n" "-c number\n", "-f filename\n","-h hostname:port\n","-n name\n","-u certificate\n","-v filename certificate\n","otherwise input will be treated as normal message"
while (True):
# get input from user
message = str(raw_input("send> "));
#Space exists and not occupies the first place
if ((message.find(" "))!= -1 and message.find(" ")>0):
if message[0:message.find(" ")] == "-a":
#if there is a space but there is nothing following -a "-a "
#or if there are more than one space following -a "-a j" or "-a h j" len(message.split(" ") return the size of array after token, need to be exactly 2;
if not message.split(" ")[1] or len(message.split(" "))>2 :
print "Usage -a filename\n"
#normal execution
else:
client.upload(message[message.find(" ")+1:])
if message[0:message.find(" ")] == "-c":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage -c number\n"
else:
print "provide the required circumference (length) of a circle of trust"
if message[0:message.find(" ")] == "-f":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage -f filename\n"
else:
client.download(message[message.find(" ")+1:])
if message[0:message.find(" ")] == "-h":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage- h hostname:port\n"
else:
print "provide the remote address hosting the oldtrusty server"
if message[0:message.find(" ")] == "-n":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage -n name\n"
else:
print "require a circle of trust to involve the named person (i.e. their certificate)"
if message[0:message.find(" ")] == "-u":
if not (message.split(" ")[1]) or len(message.split(" "))>2 :
print "Usage -u certificate\n"
else:
print "upload a certificate to the oldtrusty server"
if message[0:message.find(" ")] == "-v":
#if there are exactly two spaces "-v a b" , normal execution
if(len(message.split(" ")) == 3):
print "vouch for the authenticity of an existing file in the oldtrusty server using the indicated certificate"
else:
print "Usage: -v filename certificate\n"
elif (message == "-l"):
print "list all stored files and how they are protected"
elif(message=="-a") or (message=="-c") or (message=="-f")or (message=="-h") or (message=="-n")or (message=="-u") or (message=="-u") or (message=="-v"):
print"Usage :\n","-a filename\n" "-c number\n", "-f filename\n","-h hostname:port\n","-n name\n","-u certificate\n","-v filename certificate\n"
# exit if the input is 'exit'
elif (message == "exit"):
client.send("EXIT"+"sprt");
client.close();
time.sleep(0.01);
#Normal Commmunication
else:
print "Other situation"
print message;
client.send("NORMAL"+"sprt"+message);
if __name__=='__main__':
main()

The file you are using differs from the one you've posted here in one significant aspect: indentation. Your download method is either indented too much (that would make it defined while running upload) or too little (that would make it a module-level function, instead of one associated with timer). Make sure that the indentation around def download is correct, i.e. 4 spaces.
While you're at it, the line
downloadData = self.sock.recv();
will need some modification too. Most likely, you want something along the lines of
downloadData = self.sock.recv(4096)

Related

Telnetlib output into text file to be called on as a variable later

I have a program that i'm trying to create for the purpose of searching the network for specific mac addresses.
When I run the cisco command "show mac-address-table" it gives output that's saved to MH2. If that output has "000c." in it all the output is saved into a txt file that i'm hoping i'll be able to filter through and pull the vlan from based on the command used (show mac address-table vs show mac-address-table) as the vlan location for the line with the mac address could be to the left or the right. I'm planning on figuring that part out later, but for now it doesn't seem that my script is reading the file(which is getting the correct output and has a "000c." entry in it) I'll enter the code below:
#!/usr/bin/env python3
from time import sleep
import telnetlib
from getpass import getpass
# f is the .txt document that lists the IP's we'll be using.
f = open("devicess.txt")
#
username = input("please provide your username:")
password = getpass()
#
for line in f:
device = (line)
print('Starting to collect information, please wait')
#For those devices in the above list, connect and run the below commands
def loopstart():
for device in f:
tn = telnetlib.Telnet()
tn.open(device, 23, 20)
#Remove # in the line below for debug
#tn.set_debuglevel(2000)
tn.read_until(b"Username:", timeout = 20)
sleep(.25)
tn.write(str(username + "\n").encode("ascii"))
sleep(.25)
tn.read_until(b"Password: ", timeout = 10)
sleep(.25)
tn.write((password + "\n").encode("ascii"))
sleep(.25)
#####################################
#Verify Login attempt below #
#####################################
try:
enablemode = tn.read_until(b"#")
if (b"FAIL") in enablemode:
print("Bad credentials to " + device)
tn.close()
sleep(.5)
elif (b"fail") in enablemode:
print("Bad credentials to " + device)
tn.close()
sleep(.5)
elif (b"#") in enablemode:
print("connection established to " + device)
try:
tn.write(str("show mac address-table | include 000c.\n").encode('ascii'))
sleep(2)
MH2 = tn.read_very_eager()
if (b"000c.15") in MH2:
try:
sleep(.5)
mactable = open("mactable.txt", "rb+")
mactable.seek(0)
mactable.write(MH2)
mactable.truncate()
OP1 = mactable.read
for line in OP1():
CPMAC = (line)
try:
if (b"000c.15") in CPMAC:
print("line 70 in use")
print((CPMAC) + " this is what vlan the cyber power device should be on")
tn.write(str("show interface vlan" + (CPMAC[:6]) + "\n")).encode("ascii")
tn.read_until(b"Internet Address")
tn.close()
elif (str("All")) in (CPMAC):
print ("CPU has matching MAC, moving to next device")
tn.close()
else:
print("No Cyber power device found on " + device)
tn.close()
except EOFError as e:
print("could not pull vlan from output")
except EOFError as e:
print("unidentified issue")
#Execute the following commands in case of invalid command input
elif (b"Invalid") in MH2:
sleep(.5)
try:
tn.write(str("show mac-address-table | in 000c.\n").encode('ascii'))
sleep(2)
MH3 = tn.read_very_eager()
if (b"000c.15") in MH3:
print("Line 90 in use")
try:
sleep(.5)
mactable = open("mactable.txt", "r+")
mactable.seek(0)
mactable.write(str(MH3))
OP2 = (mactable.read())
print (type(OP2))
mactable.truncate()
for line in OP2():
CPMAC = (line)
try:
if ("000c.15") in (CPMAC):
print((CPMAC) + " this is what vlan the cyber power device should be on")
tn.write(str("show interface vlan" + (CPMAC[:6])+ "\n").encode("ascii"))
tn.read_until(b"Internet Address")
tn.close()
elif (str("All")) in (CPMAC):
print ("CPU has matching MAC, moving to next device")
tn.close()
else:
print("No Cyber power device found on " + device)
tn.close()
except EOFError as e:
print("could not pull vlan from output")
except EOFError as e:
print("unidentified issue")
elif (b"000c.15") not in MH3:
print ("Cyber power device not found, moving to next device.")
tn.close()
else:
print("Unknown Error")
tn.close()
##############################
# Logout commands #
##############################
except EOFError as e:
print("Connection closed to " + device)
else:
tn.write(str("exit\n").encode('ascii'))
tn.write(str("exit\n").encode('ascii'))
tn.close()
print(tn.read_all().decode('ascii'))
except EOFError as e:
print ("unknown error")
else:
tn.close()
except EOFError as e:
print("Connection closed to " + device)
except Exception as exception:
print(exception, False)
tn.close()
loopstart()
print('script complete')
"if ("000c.15") in (CPMAC)" is the part of the code that I believe i'm having trouble with. any help is appreciated!
Not really sure what you are trying to achieve but check the line OP1 = mactable.read read is a function that should be written as OP1 = mactable.read()
So the below is what has worked for me so far, I'm able to run the command "show mac address-table", take that output and put it into a text file, search line by line through the output for 000c.15 and use that line for further output later down the road. I think the important thing was to decode the output(bytes) into a string before writing it to the text file. Also, using the seek(0) function was helpful for taking me back to the beginning of the txt file before starting to read. Line.strip seems to get rid of all the white space being interpreted as lines. not 100% sure on that last one. Still having issues with getting that code to send the command but i'm making progress at least. Thanks everyone for your help.
if (b"000c.15") in MH2:
print("000c.15 in MH2, line 57")
try:
print ("line 59")
sleep(.5)
mactable = open("mactable.txt", "w+")
mactable.seek(0)
mactable.write(MH2.decode('utf-8'))
mactable.truncate()
mactable.seek(0)
OP1 = mactable.readlines()
for line in OP1:
line = line.strip()
CPMAC = line

Function and arguments Issue | Unable to send command and connect to network device using python script?

Unable to produce from the device, made a separate function in running a simple method wherein I have a list of devices and command.
But from this script, seems like I can't send the command to the device? I'm not sure whether script can connect successfully. So I put a print on connect to device part just to determine the location.
From the output of the print is
Connected 0 <-from beg_rm
THIS IS THE COMMAND show ip int brief <-send_cmd
Would like to ask if my method is correct in connect and sending command using this function and argument?
#!/usr/bin/python2
#Required Modules
import sys
sys.path.append("/home/lab/Desktop/pexpect-2.3")
import sys, pexpect, re, getpass, threading, subprocess, os, time
#from queue import Queue
os.system("clear")
### TEST THE IP ADDRESS IF REACHABLE
def ping_ip(ip):
#global gips
rstlongstr = ''
(output,error) = subprocess.Popen((['ping', ip, '-c', '2']), stdin=subprocess.PIPE, stdout=subprocess.PIPE).communicate()
if b'bytes from' in output:
#rstlongstr = rstlongstr + ip
#print rstlongstr
return "Reachable" + ip
elif b'Host Unreachable' in output:
return "Down"
else:
return "UNKNOWN"
### SEND COMMAND TO DEVICE
def send_cmd(child,com):
print "THIS IS THE COMMAND", com
child.sendline(com)
child.expect("#")
print(child.before)
return result
### CONNECT TO DEVICE
def beg_rm(ip,uname,ppass,enpass):
print "Begin remote connection",ip
print "\nCRED",uname,ppass,enpass
child = pexpect.spawn('ssh %s#%s' % (uname, ip))
i = child.expect(['[P|p]assword: ','[U|u]sername: ','continue connecting (yes/no)?','#'],timeout=5)
if i == 0:
child.sendline(ppass)
child.expect('>')
child.sendline('enable')
child.expect('Password: ')
child.sendline(enpass)
print "Connected 0"
return i
elif i == 1:
child.sendline(uname)
child.expect('Password: ')
child.sendline(ppass)
child.expect('>')
child.sendline(enpass)
print "Connected 1"
return i
elif i == 2:
child.sendline('yes')
i = child.expect([pexpect.TIMEOUT, '[P|p]assword: '])
if i == 0:
print "Error connecting ",ip
return
child.sendline(ppass)
child.expect('>')
child.sendline('enable')
child.expect('Password: ')
child.sendline(enpass)
print "Connected 2"
return i
elif i == 3:
pass
def main():
print('-'*50)
while True:
print('------------------------- ue Network Tools -------------------------------')
print('--- *********************************************************************** ---')
print('-'*80)
print'[1] Troubleshoot'
print'[2] Custom Tshoot'
print'[3] Wireless LAN'
print'[4] Confinder'
print'[q] exit\n'
#Select Function
input_select = raw_input('Please select a function: ')
input_select = str(input_select)
if input_select == 'q' or input_select == 'Q':
sys.exit()
elif input_select == '1':
#Read the txt file
devtxt = open('devices.txt')
devlist = devtxt.read().splitlines()
print devlist
cmdtxt = open('command.txt')
cmdlist = cmdtxt.read().splitlines()
print cmdlist
#tuname = raw_input("TACACS Username: ")
#tpass=getpass.getpass("TACACS Password: ")
#epass=getpass.getpass("Enable Password: ")
tuname = "test"
tpass = "test"
epass = "enter"
#LIST
gips = []
threadslist = []
#Verify Reachability
for ips in devlist:
print "Processing the list to function", ips
response = ping_ip(ips)
result = ('%s \n' % (response))
print result
if re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',str(response)):
forgips = re.findall(r'(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})',str(response))
strgips = ''.join(forgips)
#print "FORGIPS 2",strgips
gips.append(strgips)
pass
else:
pass
print "\nList of reachable devices to be sent for threading:\n", gips
## LOOP REACHABLE DEVICE AND COMMAND
for x in gips:
child = beg_rm(x,tuname,tpass,epass)
for y in cmdlist:
send_cmd(child,y)
if __name__ == '__main__':
main()
Trace back
Traceback (most recent call last):
File "2jb.py", line 142, in <module>
main()
File "2jb.py", line 139, in main
send_cmd(child,y)
File "2jb.py", line 31, in send_cmd
child.sendline(com)
AttributeError: 'int' object has no attribute 'sendline'
child = beg_rm(x,tuname,tpass,epass)
for y in cmdlist:
send_cmd(child,y)
def send_cmd(child,com):
print "THIS IS THE COMMAND", com
child.sendline(com)
...
beg_rm() returns an integer, which is then passed as the child argument to send_cmd().
It seems like you're expecting beg_rm() to return the child object, instead of an integer?

Problems while implementing file transfer with sockets in Python

I am learning Python right now, and try to write a small file transfer program. The following is my codes.
This is the server codes
import SocketServer
import commands, time
class MySockServer(SocketServer.BaseRequestHandler):
def recv_all(self,obj, msg_length, des_file):
while msg_length != 0:
if msg_length <= 1024:
print 'here3'
print msg_length
print type(msg_length)
data = obj.recv(msg_length)
print data
msg_length = 0
print 'here4'
break
else:
data = obj.recv(1024)
msg_length -= 1024
#print msg_length
des_file.write(data)
print 'here4'
return 'Done'
def handle(self):
print 'Got a new conn from', self.client_address
while True:
cmd = self.request.recv(1024)#receive data from client
print cmd
if not cmd:#deal with ctrl+c from client
print 'Lost connection'
break
CMD = cmd.split()
print CMD
option, filename, file_size = CMD[:3]
print option
print filename
print file_size
if option == 'put':
#client wants to upload file
f = file('temp/%s' % filename, 'wb')
print 'here'
write_to_file = self.recv_all(self.request, int(file_size), f)
print 'here1'
if write_to_file == 'Done':
f.close()
self.request.send('File uploading done')
if __name__ == '__main__':
h = '0.0.0.0'
p = 9002
s = SocketServer.ThreadingTCPServer((h,p),MySockServer)
s.serve_forever()
The client codes:
import socket, os
host,port = '192.168.73.11', 9002
c = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
c.connect((host,port))
while True:
user_input = raw_input('msg to send:: ').strip()
if len(user_input) == 0: continue
user_cmd = user_input.split()
if user_cmd[0] == 'put':
if len(user_cmd) == 2:
f = file(user_cmd[1], 'rb')
f_size = os.path.getsize(user_cmd[1])
print user_cmd[0], user_cmd[1], str(f_size)
c.send('%s %s %s ' % (user_cmd[0],user_cmd[1],f_size))
print 'going to send....'
c.sendall(f.read())
print c.recv(1024)
c.close()
I just inserted some prints into the codes to find where are the problems. I found that in the recv_all() function in server codes, the sentence 'data = obj.recv(msg_length)' in the 'if' part cannot work, but the sentence in the 'else' part works very well. Is there anyone can tell me why could this happen?
Thanks guys.

<BEA-050001> WLContext.close() was called in a different thread than the one in which it was created

I have written wlst script to achieve the below tasks recursively
Stopping the applications
Undeploying the applications
Deploying the appliactions
When ever i execute the script, Either undeploy or Deploy happens only for 1 application. For other applications it fails with below error message.Can you please help me to fix the issue?
File "<iostream>", line 1116, in domainConfig
File "<iostream>", line 1848, in raiseWLSTException
WLSTException: Error cding to the MBean
<Feb 20, 2014 11:28:44 AM IST> <Warning> <JNDI> <BEA-050001> <WLContext.close() was called in a different thread than the one in which it was created.>
WLST Script what i have written
import sys
import os
import getopt
#========================
#Usage Section
#========================
def usage():
print "Usage:"
print "java weblogic.WLST manageApplication.py -u username -p password -a adminUrl [<hostname>:<port>] -t deploymentTarget\n"
print "java weblogic.WLST manageApplication.py -u weblogic -p weblogic1 -a t3://localhost:7001 -t AdminServer\n"
sys.exit(2)
#========================
#Connect To Domain
#========================
def connectToDomain():
try:
connect('weblogic','weblogic1','t3://localhost:7001')
print 'Successfully connected to the domain\n'
except:
print 'The domain is unreacheable. Please try again\n'
exit()
#========================
#Application undeployment Section
#========================
def undeployApplication():
cd ('AppDeployments')
myapps=cmo.getAppDeployments()
for appName in myapps:
domainConfig()
cd ('/AppDeployments/'+appName.getName()+'/Targets')
mytargets = ls(returnMap='true')
domainRuntime()
cd('AppRuntimeStateRuntime')
cd('AppRuntimeStateRuntime')
for targetinst in mytargets:
curstate4=cmo.getCurrentState(appName.getName(),targetinst)
print '-----------', curstate4, '-----------', appName.getName()
deploymentName=appName.getName()
deploymentTarget=targetinst
print deploymentName
print deploymentTarget
stopApplication(deploymentName, targets=deploymentTarget)
undeploy(deploymentName, targets=deploymentTarget)
#========================
#Input Values Validation Section
#========================
if __name__=='__main__' or __name__== 'main':
try:
opts, args = getopt.getopt(sys.argv[1:], "u:p:a:t:", ["username=", "password=", "adminUrl=", "deploymentTarget="])
except getopt.GetoptError, err:
print str(err)
username = ''
password = ''
adminUrl = ''
deploymentTarget = ''
for opt, arg in opts:
if opt == "-u":
username = arg
elif opt == "-p":
password = arg
elif opt == "-a":
adminUrl = arg
elif opt == "-t":
deploymentTarget = arg
if username == "":
print "Missing \"-u username\" parameter.\n"
usage()
elif password == "":
print "Missing \"-p password\" parameter.\n"
usage()
elif adminUrl == "":
print "Missing \"-a adminUrl\" parameter.\n"
usage()
elif deploymentTarget == "":
print "Missing \"-c deploymentTarget\" parameter.\n"
usage()
#========================
#Main Control Block For Operations
#========================
def deployMain():
for line in open("c:\\wlst\\applicationsList.txt"):
temp_line = line
fields = temp_line.strip().split(",")
print(fields[0]+" "+fields[1])
deploymentName = fields[0]
deploymentFile = fields[1]
print deploymentName+" "+deploymentFile+" "+deploymentTarget+"/n"
deploy(deploymentName,deploymentFile,targets=deploymentTarget)
#==================
#main block
#=====================
connectToDomain()
undeployApplication()
deployMain()
disconnect()
WLContext.close() is probably not the real problem (it's even in some of the Oracle examples). What error messages do you see when deploy and undeploy are being called?
You should see something like:
Deploying application from /tmp/something/myapp.ear
Current Status of your Deployment:
Deployment command type: deploy
Deployment State : completed
Deployment Message : no message
I also see that you never call activate() at the very end of your script so that could be the issue if you are running in production mode.
Try adding the following at the very end of your script after deployMain():
save()
status = activate(300000, "block='true'")
status.getStatusByServer()
status.getDetails()
UPDATE:
The activation error occurs because you have not called edit() before the undeploy:
# Get edit/lock for upcoming changes
edit()
startEdit(120000, 120000, 'false')
undeployApplication()
I think you will be better off greatly simplifying your undeploy. You don't need to go through the complexity of determining targets because you are already undeploying from ALL targets. Try this instead and see if you can make progress:
cd ('AppDeployments')
myapps=cmo.getAppDeployments()
for appName in myapps:
try:
appPath = "/AppDeployments/" + appName.getName()
cd(appPath)
print "Stopping deployment " + appName.getName()
stopApplication(appName.getName())
print "Undeploying " + appName.getName()
undeploy(appName.getName(), timeout=60000)
except Exception , e:
print "Deployment " + appName.getName() + " removal failed."

Unindent does not match any outer indentation level

On line 51/52, I get the error:
Unindent does not match any outer indentation level.
I understand this has something to do with tabs and spaces.
Note I did not write this code, I found it online and plan to modify it.
Full code (also at http://pastebin.com/n7ML6Rpz)
import os
import re
import socket
import sys
import time
server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Create socket
server_socket.bind(("", 9020)) #Bind server to this socket
server_socket.listen(4) #Max number of queued connections
# Welcome message
print ("TCP chat server now awaiting client connection on port 9020...")
chat_log = [] #Contains chat log
time = time.strftime('%l:%M %p %Z on %b %d, %Y') #Server start time formatted nicely
start_time = str(time) #Convert server start time to string
username = "ChatUser" #Default server username if user does not provide one
# Support ~2^x client connections, where x is the number of process forks
os.fork()
os.fork()
os.fork()
# This variable contains the help documentation for the "help" command
chatHelp = ("The chat server accepts the following commands:\n"
+ "adios Closes the program\n"
+ "connection Shows client connection info (IP, port)\n"
+ "get Returns complete chat log\n"
+ "getrange <#> <#> Get chat log entries from <#> to <#> (starts at 1)\n"
+ "help Lists valid commands\n"
+ "name: <text> Sets your username to <text>\n"
+ "test: <text> Echo data back to you <text>\n"
+ "time Shows time when server was initiated\n"
+ "push: <text> Add <text> to chat log\n"
+ "save Save chat log to file\n")
while 1:
# Accept connection
client_socket, address = server_socket.accept()
# Print connection info from client for server log
print ("Received connection from client at"), address
# Used in the connection command function (client request) below
connection = str(address)
# Send welcome string to client
client_socket.send("Welcome to Nigel's chat room! You are logged in as ChatUser.\n Type help for a list of valid commands.\n")
# Loop indefinitely while server running
while 1:
data = client_socket.recv(2048) #Receive client data into buffer
process_data = data.lower() #Lowercase received data for processing
print ("Data received from client>>"), process_data #Print data received from client for log reference
# Functions for the received commands (I use the find library to reduce compatibility errors with other languages)
# ---"adios" command function---
if (process_data.find("adios") == 0):
client_socket.close() #Close socket connection
print ("<Ctrl+C to exit.>>")
break;
# ---"connection:" command function---
elif(process_data.find("connection") == 0):
client_socket.send("Client connection info: " + connection + "\n")
print "User requested connection information"
# ---"getrange" command function w/ regular expression filtering (must be BEFORE "get" command function)---
elif(re.match(r'getrange\s+(\d+)\s+(\d+)',process_data)): # Regex to find correct match with dynamic numbers input
match = re.match(r'getrange\s+(\d+)\s+(\d+)',process_data)
getValue = "Chat log from range "+ match.group(1) + " and " + match.group(2) + ":\n" # Grab first and second range number provided by client
if(len(chat_log) >= int(match.group(1)) and len(chat_log) >= int(match.group(2))): # Check to see if chat log extends to given range
count = int(match.group(1)) - 1
while(count < int(match.group(2))):
getValue += chat_log[count] + "\n"
count += 1
else:
getValue += "<>\n" #No data in range provided by client
client_socket.send(getValue) #Send results to client
# ---"get" command function---
elif(process_data.find("get") == 0):
log = "Chat log: \n"
for item in chat_log:
log += item+" \n"
client_socket.send(log)
# ---"help:" command function---
elif(process_data.find("help") == 0):
client_socket.send(chatHelp + "\n")
print "User requested help"
# ---"name:" command function---
elif(process_data.find("name:") == 0):
username = data[5:].strip() #Only grab the value client set (not "name:")
client_socket.send("Username set to: " + data[5:] + "\n")
# ---"test:" command function---
elif(process_data.find("test:") == 0):
client_socket.send(data[5:]+"\n") #Echo last 5 elements to client
print data
# ---"time" command function---
elif(process_data.find("time") == 0):
client_socket.send("Chat server was started at: " + start_time + "\n")
print "User requested server start time"
# ---"save" command function---
elif(process_data.find("save") == 0):
print "(Saving chat log to file)"
client_socket.send("Saving chat log to file..." + "\n")
filename = "chat.log"
file = open(filename,"w") #Create file
for item in chat_log: #Loop through elements in chat_log
file.write("%s\n" % item) #Write elements one by one on a new line
file.close() #Close/write file
# ---"push" command function---
elif(process_data.find("push:") == 0):
print "(Pushing data to chat log)"
if(username != ""):
chat_log.append(username + ": " + data[5:].strip()) #Save actual chat text to log (not "push:")
else:
chat_log.append(data[5:].strip())
client_socket.send("OK\n")
else:
print "<<Unknown Data Received>>",data #Server log
try:
client_socket.send("Unrecognized command: " + data + "") #Advise client of invalid command
except socket.error, e:
print "<<Ctrl+C to exit>>" #Server log
break;
Python code is sensitive to the indent level you use. Your code reads:
if (process_data.find("adios") == 0):
client_socket.close() #Close socket connection
print ("<Ctrl+C to exit.>>")
break;
Inside the if block, the statements must all line up. Notice how client_socket.close() and the following print statement have different indent levels. You need to change this so that they both have the same indent, like this:
if (process_data.find("adios") == 0):
client_socket.close() #Close socket connection
print ("<Ctrl+C to exit.>>")
break;
The code presently reads:
if (process_data.find("adios") == 0):
client_socket.close() #Close socket connection
print ("<Ctrl+C to exit.>>")
break;
The first statement in the body of the if is indented 6 spaces, while the last two statements are only indented by 1 space. The indentation level ought to be same and consistent throughout the program, something like this:
if (process_data.find("adios") == 0):
client_socket.close() #Close socket connection
print ("<Ctrl+C to exit.>>")
break;
The indentation in the code doesn't seem very standard (or consistent). For instance the body of the while loop in 41/42 is indented more than other bodies of similar statements, e.g., lines 31-33, that's trouble in a language like Python where whitespace matters.
Finally, note it's not a good idea to mix tabs and spaces. PEP 8 -- Style Guide for Python Code recommends the use of spaces over tabs and an indentation of 4 spaces per level.

Categories