So I'm writing a simple socket program. The client sends a directory path to the server. 'data' is the given directory path. In the example below, it takes the path given and runs the Linux command 'ls -l path'.
while True:
print (data.decode())
batcmd=('ls -l ' + data.decode())
result = os.system(batcmd)
So if the client entered '/home/user', the shell command 'ls -l /home/user' will run and display the contents and permissions of the directory.
Now I want to sort through the result and fine a particular word. Then display the line that contains that word. For example, one line contains the word "Pictures". So I want to display that line which is
drwxr-xr-x 3 myname myname 4096 Feb 25 2017 Pictures
If I try this:
import subprocess
import os
from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM
import sys
PORT_NUMBER = 2000
SIZE = 1024
hostName = gethostbyname( '0.0.0.0' )
mySocket = socket( AF_INET, SOCK_DGRAM )
mySocket.bind( (hostName, PORT_NUMBER) )
print ("Test server listening on port {0}\n".format(PORT_NUMBER))
# Receive no more than 1024 bytes
while True:
(data,addr) = mySocket.recvfrom(SIZE)
try:
print >>sys.stderr, 'Received data from', addr
while True:
print (data.decode())
batcmd=('ls -l ' + data.decode())
result = os.system(batcmd)
word = "Pictures"
print result.find(word)
# Do other stuff here
finally:
print >> sys.stderr, 'closing socket'
sys.exit()
I get the error "AttributeError: 'int' object has no attribute 'find'"
If I try this:
import subprocess
import os
from socket import socket, gethostbyname, AF_INET, SOCK_DGRAM
import sys
PORT_NUMBER = 2000
SIZE = 1024
hostName = gethostbyname( '0.0.0.0' )
mySocket = socket( AF_INET, SOCK_DGRAM )
mySocket.bind( (hostName, PORT_NUMBER) )
print ("Test server listening on port {0}\n".format(PORT_NUMBER))
# Receive no more than 1024 bytes
while True:
(data,addr) = mySocket.recvfrom(SIZE)
try:
print >>sys.stderr, 'Received data from', addr
while True:
print (data.decode())
batcmd=('ls -l ' + data.decode())
result = os.system(batcmd)
word = "pictures"
for line in result:
search_res = word(line)
print line
if search_res is None:
print ("That word does not exist.")
break
else:
print ("something else")
# Do other stuff
finally:
print >> sys.stderr, 'closing socket'
sys.exit()
I get TypeError: 'int' object is not iterable
What is the best way to go about finding a word and printing the line that word is contained in?
Do I need to dump result into a file in order to handle it?