Trying to get a handle on the FTP library in Python. :)
Got this so far.
from ftplib import FTP
server = '127.0.0.1'
port = '57422'
print 'FTP Client (' + server + ') port: ' + port
try:
ftp = FTP()
ftp.connect(server, port, 3)
print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"'
ftp.cwd('\\')
x = '1'
currentDir = ''
except: //***What do I put here?***
http://docs.python.org/library/ftplib.html
says there are several error codes I can catch but I can't do
except: ftplib.all_errors
Second question. :P
How can I retrieve more specific information on the error? Perhaps the error code?
Very new to python (an hour in or so).
I can't do
except: ftplib.all_errors
Of course not, that's simply bad syntax! But of course you can do it with proper syntax:
except ftplib.all_errors:
i.e., the colon after the tuple of exceptions.
How can I retrieve more specific
information on the error? Perhaps the
error code?
except ftplib.all_errors as e:
errorcode_string = str(e).split(None, 1)[0]
E.g., '530' will now be the value of errorcode_string when the complete error message was '530 Login authentication failed'.
You can find the rest of the exception in the docs.
You write
except Exception, e: #you can specify type of Exception also
print str(e)
You dont want to try catch an Exception class unless you have to. Exception is a catch all, instead catch the specific class being thrown, socket.error
import ftplib
import socket <--
server = '127.0.0.1'
port = '57422'
print 'FTP Client (' + server + ') port: ' + port
ftp = ftplib.FTP()
try:
ftp.connect(server, port, 3)
print 'Connected! Welcome msg is \"' + ftp.getwelcome() + '\"'
ftp.cwd('\\')
x = '1'
currentDir = ''
except socket.error,e: <--
print 'unable to connect!,%s'%e
Related
I want to build a Python program to check the NSlookup result.
In my program, I want to output like:-
If I input google then it will show “not unique” as output, but
when I provide input like Rajat then the output will be unique because rajat.com is not a valid site (invalid URL no IP is linked with this URL)
Below is my code.in this code will show not unique when I input google but throw an error when I input Rajat.
So I just want to know how to handle this error or how we can get the output as unique when the program throws an error.
import socket
dns=input("Enter DNS: ")
result= socket.gethostbyname(dns+".com")
if not result:
print("Unique")
else:
print("Not Unique")
The gethostbyname() function raises the socket.gaierror exception if the given hostname is not found, so you have an opportunity to catch it and perform what you want:
import socket
dns=input("Enter DNS: ")
try:
result= socket.gethostbyname(dns + ".com")
except socket.gaierror:
print("Unique")
else:
print("Not Unique"))
Note:
In my humble opinion the better messages would be something as “Not used” / “Used” or
“Not found” / “Found”. Yours are a little confusing.
You can use try-except to catch an error. In this code snippet we try to connect to the given domain and if the connection is successful (the website exists) it prints Not unique, if not, it prints Unique.
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
dns = input("Enter DNS: ")
try:
s.connect((dns + ".com", 80))
except Exception as e:
print("Unique")
else:
print("Not unique")
I'm just learning python and I've got a noobquestion here. What I want to do is loop the given IP addresses (192.168.43.215 through .218) and run given commands. The first host works as it can connect, while the second (.216) cannot be connected to and then the script exits with a "socket.error: [Errno 111] Connection refused" error.
I don't want it to exit the script, but to keep running on the remaining hosts. So how do I handle this exception to keep the for loop running?
#!/usr/bin/python
import socket
import sys
usernames = ["root", "admin", "robot", "email"]
for host in range(215,218):
ipaddress = "192.168.43." + str(host)
print ipaddress
# Create a socket
s=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.settimeout(10)
# Connect to the server
connect=s.connect((ipaddress,25))
# Receieve the banner
banner=s.recv(1024)
print banner
for x in usernames:
# Verify a user
s.send('VRFY ' + x + '\r\n')
result=s.recv(1024)
print result
# Close the socket
s.close()
print "All hosts completed."
Sounds like you just need some basic error handling with a try/except block:
try:
# run dangerous operation
except TheExceptionThatCouldBeTriggered:
print("An exception was triggered... continuing")
else:
# do other stuff if dangerous operation succeeded
In your case, you want to except socket.error
I am attempting to create a Python web server however it seems to not be able to send any files larger then 4KB. If the file is above 4KB in size it just cuts off the end of the text/image past 4KB. Anything embedded from other sources (Amazon S3/Twitter) work fine.
Here is the server code. It is a bit of a mess at the moment but I am focused on getting it to work. Afterwards I will add more security to the code.
'''
Simple socket server using threads
'''
import socket
import sys
import time
import os
from thread import *
HOST = '' # Symbolic name meaning all available interfaces
PORT = 80 # Arbitrary non-privileged port
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print 'Socket created'
#Bind socket to local host and port
try:
s.bind((HOST, PORT))
except socket.error as msg:
print 'Bind failed. Error Code : ' + str(msg[0]) + ' Message ' + msg[1]
sys.exit()
print 'Socket bind complete'
#Start listening on socket
s.listen(10)
print 'Socket now listening'
#Function for handling connections. This will be used to create threads
def clientthread(conn):
#Sending message to connected client
#infinite loop so that function do not terminate and thread do not end.
while True:
#Receiving from client
data = conn.recv(4096)
print data
dataSplit = data.split(' ')
print dataSplit
contentType = "text/html"
if(dataSplit[1].endswith(".html")):
print "HTML FILE DETECTED"
contentType = "text/html"
elif(dataSplit[1].endswith(".png")):
print "PNG FILE DETECTED"
contentType = "image/png"
elif(dataSplit[1].endswith(".css")):
print "CSS FILE DETECTED"
contentType = "text/css"
else:
print "NO MIMETYPE DEFINED"
conn.sendall('HTTP/1.1 200 OK\nServer: TestWebServ/0.0.1\nContent-Length: ' + str(os.path.getsize('index.html')) + '\nConnection: close\nContent-Type:' + contentType + '\n\n')
print '\n\n\n\n\n\n\n\n'
with open(dataSplit[1][1:]) as f:
fileText = f.read()
n = 1000
fileSplitToSend = [fileText[i:i+n] for i in range(0, len(fileText), n)]
for lineToSend in fileSplitToSend:
conn.sendall(lineToSend)
break
if not data:
break
#came out of loop
conn.close()
#now keep talking with the client
while 1:
#wait to accept a connection - blocking call
conn, addr = s.accept()
print 'Connected with ' + addr[0] + ':' + str(addr[1])
#start new thread takes 1st argument as a function name to be run, second is the tuple of arguments to the function.
start_new_thread(clientthread ,(conn,))
s.close
Thank you for your time.
So, thanks you the user "YOU" we found the problem. I had this code:
conn.sendall('HTTP/1.1 200 OK\nServer: TestWebServ/0.0.1\nContent-Length: ' + str(os.path.getsize('index.html')) + '\nConnection: close\nContent-Type:' + contentType + '\n\n')
instead of this code:
conn.sendall('HTTP/1.1 200 OK\nServer: TestWebServ/0.0.1\nContent-Length: ' + str(os.path.getsize(dataSplit[1][1:])) + '\nConnection: close\nContent-Type:' + contentType + '\n\n')
The problem was that I was sending the file size for index.html for every file, so Chrome and other browsers just removed the extra data. It just so happened index.html was 4KB so I though it was a packet limitation or something in that area.
I'm working on a python client which is supposed to converse with a C programmed server. For now it just answers a few recognised commands with "ok" (the server part works when I test it with netcat as the client). But my python client only gets the ok 1 out of four times (and empty lines the rest of the time). I don't get why as the socket is set as blocking so I figure it does receive something but I don't know what.
Here is what I have. "info" is just an object with a few strings stored in it, everything before the loop works and a bit simplified for readability : I'm just supposed to receive a welcome message then send back the team name of the connected player then receive a position.
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print 'Failed to create socket. Error code: ' + str(msg[0]) + ' , Error message : ' + msg[1]
sys.exit();
try:
remote_ip = socket.gethostbyname(info.host)
except socket.gaierror:
print "Hostname could not be resolved. Exiting"
sys.exit()
s.setblocking(1)
s.settimeout(60)
s.connect((remote_ip, info.port))
data = s.recv(1024)
print data
team = info.team + "\n"
s.sendall(team)
data = s.recv(1024)
print data
while 42:
msg = raw_input('>> ')
s.sendall(msg + "\n")
data = s.recv(1024)
if data == "":
break
else:
print data
s.shutdown(socket.SHUT_WR)
s.close()
It seems to me you do receive something : cast data to ascii with ord() to see it. My guess is that there's 3 unprintable lines before the "ok" in the response the server sends you. Just identify then catch them in a new loop.
I have the following code that is part of my email class that I use in my programs. Currently I am running the quit function whether or not a connection to the SMTP server was made in the connect function. I know I could put the quit function inside of the try statement after the email is sent, but I would like to figure out how to write the code to say the equivalent of "if a connection to the server is open, close it." What is the best way to write that in Python?
Thanks!
def connect(self, headers, msg):
try:
self.server.starttls()
try:
self.server.login(self.usrname,self.pswd)
try:
self.server.sendmail(self.sendfrom, self.sendto, headers + "\r\n\r\n" + msg)
except Exception as sendmailfail:
print(sendmailfail)
except Exception as emailfail:
print (emailfail)
except Exception as error:
print(error)
def quit(self):
self.server.quit()
print("The SMTP connection is closed")
first = GmailSmpt('x','y','z','zz')
x , y = first.message()
first.connect(x,y)
first.quit()
You need to finish the "Errors and Exceptions" section of the tutorial.
try:
possibly_fail()
except ...:
handle_exception()
else:
no_exceptions()
finally:
always_run_this()