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
Related
I'm following a Python tut on writing a port scanner, it runs, but it seemed to skip over a port that should theoretically be open. I'm running a web browser so port 80 should be up, but when I ran it against my network it just skipped over it. Also tried it against 443, but it's not showing any HTTPS ports either.
import sys #allows us to enter cmd line arguments & other things
import socket #Sockets and the socket API are used to send messages across a network. They provide a form of inter-process communication (IPC).
from datetime import datetime
#next we need to define our target
if len(sys.argv) == 2:
target = socket.gethostbyname(sys.argv[1]) #translate host name to IPV4
else:
print (“invald amt of arguments.”)
print (“syntax: python3 scanner.py <ip>”)
sys.exit()
#add a pretty banner
print (“-” * 50)
print (“scanning target” + target)
print(“Time started: “ +str(datetime.now()))
print (“-” * 50)
try:
for port in range (50,85):
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
socket.setdefaulttimeout(1) #is a float
result = s.connect_ex((target,port)) #returns error indicator
print ((“checking port {}”).format(port)) #returns error indicator
if result ==0:
print (“port {} is open”.format(port))
s.close()
except KeyboardInterrupt:
(“\Exiting Program”)
sys.exit()
except socket.gaierror:
print (“host name could not be resolved”)
sys.exit()
except socket.error:
print (“could not connect to server”)
sys.exit()**
If You replace all smart quoutes with straight quoutes,
indent the TRUE-block of the if-statement inside the for-loop and
remove the escape character ("\") in the exception handler,
then Your code runs fine.
Here is the code,
def get_local_ip():
try:
# doesn't even have to be reachable
s.connect(('10.255.255.255', 1))
ip = s.getsockname()[0]
except Exception as err:
ip = '127.0.0.1'
finally:
s.close()
return ip
I recieve the OSError: Too many files error, If I call this function in a wsgi server. I am not too sure why this is happening since I am closing the Socket.
I have written a client-server python program where the client can send the data to the server. But when the client is trying to connect with the server I am getting the following error.
[Errno 110] Connection timed out
Sending Key to Server
Traceback (most recent call last):
File "client.py", line 43, in <module>
s.send(str(id))
socket.error: [Errno 32] Broken pipe
I tried the following solutions
Broken Pipe error and How to prevent Broken pipe error but none of them solved the issue.
Here are my client and server code
client.py
import socket
import os
import subprocess
from optparse import OptionParser
from random import randint
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket has been successfully created"
except socket.error as err:
print "socket creation failed with error %s" %(err)
# The Manager Address and port
host_ip='192.168.43.123'
port =10106
# Generates a random number say xxxx then its client id becomes 'clxxxx' and home directory made at the server as '/home/clxxxx' with permissions 700
def random_with_N_digits(n):
range_start = 10**(n-1)
range_end = (10**n)-1
return randint(range_start, range_end)
id=random_with_N_digits(4)
id="cl"+ str(id)
# Looks for a public key in .ssh folder if temp.pub not present. If not found generates a ssh public private key and sends it to manager which then copies it to the server
subprocess.call(["bash","keygen.sh"])
#s = socket.socket()
try:
s.connect((host_ip,port))
print "the socket has successfully connected to Backup Server IP == %s" %(host_ip)
except socket.error as err:
print err
f = open('temp.pub','r')
print "Sending Key to Server"
j = "-"
s.send(str(id))
l=f.read(8192)
while(l):
print 'Sending...'
s.send(l)
l = f.read(8192)
try:
client_id=s.recv(1024)
data=s.recv(12)
ip=s.recv(24)
print client_id,
print data, ip
except:
print "An Unknown Error Occurred!"
f.close()
# Writes the parameters of client in the file 'backup_dir.txt'
with open('backup_dir.txt','w') as the_file:
the_file.write(client_id)
the_file.write('\n')
the_file.write(data)
the_file.write('\n')
the_file.write(ip)
the_file.write('\n')
f.close()
s.close()
server.py
import socket
import subprocess
import os
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
print "Socket has been successfully created"
except socket.error as err:
print "socket creation failed with error %s" %(err)
port = 10106
s.bind(('', port))
print("socket binded to %s port" %port)
s.listen(10)
print("socket is listening")
while(True):
print("waiting for a connection")
c, addr = s.accept()
print("Got a connection from", addr,c)
clientID =(c.recv(8192))
key =(c.recv(8192))
print clientID
print key
with open("temp.pub", 'w') as fp:
fp.write(key)
note=subprocess.check_output("./test_user.sh "+ clientID, shell=True)
note = str(note)
print(len(note))
flag, path, serverIP = note.split(":")
print(flag)
print(path)
print(serverIP)
if flag:
c.send(clientID)
c.send(path)
c.send(serverIP)
os.remove("temp.pub")
else:
c.send("Unable to add Client.")
How do I fix this problem so that the client can send the data to the server without any error?
Thank You in advance.
The error resolved.
It was due to the firewall issue as #RaymondNijland was mentioning, Thanks.
I added the rule in the firewall to allow the following port for Socket Connection and it worked.
sudo ufw allow 10106
I have a Python (2.7) script which is reading realtime data from a file and publishing it (via network) to a server living on a different computer. This server, in particular, is a Carbon server part of graphite.
The relevant part of the code is as follows:
import socket
CARBON_HOST = 'COMPUTER-NAME'
CARBON-PORT = 2003
CARBON_PATH = 'folder.name.meaurement'
s = socket.socket()
s.connect((CARBON_HOST, CARBON_PORT))
while True:
if s:
s.send('%s %s %s\n'%(CARBON_PATH, str(data), int(time.time())))
time.sleep(WAIT)
where data is the latest entry imported from my file, and time is the usual.
When I switch off the computer COMPUTER-NAME where the Carbon server lives, this error appears:
s.send('%s %s %s\n'%(CARBON_PATH, str(data), int(time.time())))
socket.error: [Errno 10053] An established connection was aborted by the software in your host machine
When I restart the host machine (COMPUTER-NAME), I have to restart the Python script for data to be sent over again.
Is there a way I can tell the socket to pause if it sees it's disconnected, or to keep trying until the connection is open again?
You can't use the same socket after a socket.error exception, the connection is broken. However, you can catch the exception, create a new connection, and use that to send the data.
About your last question, you can tell your program to keep trying until the data is sent with a while loop. A basic example,
import socket
import time
CARBON_HOST = 'COMPUTER-NAME'
CARBON_PORT = 2003
CARBON_PATH = 'folder.name.meaurement'
WAIT = 10
s = socket.socket()
s.connect((CARBON_HOST, CARBON_PORT))
data = 'my data'
while True:
packet = '%s %s %s'%(CARBON_PATH, str(data), int(time.time()))
while True:
try:
s.send(packet)
break
except socket.error as e:
print(e)
s.close()
s = socket.socket()
s.connect_ex((CARBON_HOST, CARBON_PORT))
time.sleep(WAIT)
s.close()
I recommend to read about socket.timeout("seconds to sleep") which will give you idea of using it. In your case, use socket.settimeout() right before making a socket connection, and socket.settimeout(None) soon after socket.connection().
In this way, you can delay establishing connection. But if timeout value goes beyond system/server down time, then script will eventually come out with same timeout error.
connect_timeout = 100 #in seconds
socket.settimeout(connect_timeout)
socket.connect()
socket.settimeout(None)
Check if that works?
I keep getting this error
[Errno 10061] No connection could be made because the target machine actively refused it.
I'm running Windows 7 64 bit, no virus or protection software, and python is allowed through my firewall (I've also tried turning my firewall completely off but same result). When I run the server and use telnet it connects just fine. When I try to connect to the server with the client it fails. Any suggestions as to what I could try to fix this? If you need more information just ask and I'll provide.
Client Code
import socket
import sys
def main():
host = ""
port = 8934
message = "Hello World!"
host = raw_input("Enter IP: ")
#Create Socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error, msg:
print "Failed to create socket. Error code: %s Error Message: %s"%(str(msg[0]),msg[1])
sys.exit()
print "Socket created"
#Connec to Server
print host
print port
s.connect((host,port))
print "You are connected to %s with IP adress of %s"%(host,host)
#Send Data
try:
s.sendall(message)
except socket.error:
print "Failed to send."
#Receive Data
reply = s.recv(4096)
if __name__ == "__main__":
main()
Server Code
# !usr/bin/python
import socket
import sys
HOST = ""
PORT = 8934
def main():
#Setup socket
try:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
except socket.error,msg:
print "Unable to create socket"
sys.exit()
print "Socket created."
#Bind to adress
try:
s.bind((HOST,PORT))
except socket.error,msg:
print "Bind failed. Closing..."
sys.exit()
print "Socket bound."
#Start listening
s.listen(10)
print "Socket Listening"
#Accept connection
conn, addr = s.accept()
print "Connected to %s:%s"%(addr[0],addr[1])
if __name__ == "__main__":
main()
Taking a guess at your indentation, and running your code… it works just fine.* (As long as I type in 127.0.0.1 when it asks me for the IP.)
Of course the second time I run the client (if I haven't restarted the server) I get a connection-refused error. But that's just because you've coded a server that immediately quits as soon as it gets the first connection. So the second time you run the client, there is no server, so the OS rejects the connection.
You can always run the server again, which lets you run the client one more time. (Except that the server may get a 10048 error when it tries to bind the socket, because the OS is keeping it around for the previous owner. If you see that, look at SO_REUSEADDR in the docs.)
* By "works just fine" I mean that it connects, and prints out the following before quitting:
Socket created
127.0.0.1
8934
You are connected to 127.0.0.1 with IP adress of 127.0.0.1
Obviously it never sends anything to the server or receives anything back, because the server has no send or recv calls, or anything else.