Python : file transfer giving errors - python

I am trying to send a file from a server to client but get errors. Please let me know where I am doing wrong.
This is my server code:
if msg in data.keys():
print("Requested file exists", msg)
f=open(msg,"rb")
datam= f.read(1024)
while (datam):
if(s.send(datam)):
print "sending data"
datam = f.read(1024)
s.close()
f.close
else:
print("File Not found",msg)
print("File Not found",data.keys())
c.close() # Close the connection
where msg contains the path address where file exists
c=client socket s=server socket
I want to read that file and send it to client but I get this error
Got connection from ('127.0.0.1', 42330)
('Requested file exists', '/home/beenish/Pictures/pew.txt')
Traceback (most recent call last):
File "server.py", line 41, in <module>
if(s.send(datam)):
socket.error: [Errno 32] Broken pipe
On client side, I have written this code to recieve that file
s.listen(15)
f = open('\home\beenish\pictures\lol.txt', 'wb')
data = s.recv(1024)
while(data):
f.write(data)
data=s.recv(1024)
f.close()
s.close # Close the socket when done
where s is the client socket
Here I get this error
Traceback (most recent call last):
File "client.py", line 26, in <module>
s.listen(15)
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 22] Invalid argument

On the client side you have an error on this line:
s.listen(15)
And the Python docs say that the argument has a system dependant maximum, usually 5. So try finding out the maximum for your system of just use a lower value and see what happen.
The server side error could be a side effect of the client side failure.

That is the kind of error you get when you call socket.listen before calling socket.bind. Keep in mind that a server always has to follow the sequence socket(), bind(), listen() and accept() in that specific order.

Related

Receive data from a client/server doesn't work

I developed a small Python program which should receive and output data from another client or server. However, I get an error message which is unknown to me. Can anyone help me? Thanks a lot
import socket
client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
client.connect(('192.168.1.34', 80))
from_server = client.recv(4096)
client.close()
print from_server
Error:
Traceback (most recent call last):
File "CallManager2.py", line 4, in <module>
client.connect(('192.168.1.34', 80))
File "/usr/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 111] Connection refused
The error comes from inability for your program to reach the server or other client.
Check that there is something listening to incoming connexions on the address you want to connect to.
Then you can check that the address you want to connect to is on the same network as your program.

Paramiko stuck on for loop

I need to perform a remote software update for a Linux device.
I'm able to upload via SSH and SFTP to /tmp/ folder the .bin file and perform the sysupgrade.
I want to do this on multiple device, so I added a for loop in order to do it.
But, when I run the ssh.exec_command("sysupgrade /tmp/myfile.bin"), something stucks.
Here's my code:
import paramiko
# paths to file
local_path="C:/Users/Desktop/myfile.bin"
remote_path="/tmp/myfile.bin"
# IP
ip_list = ["my_ip_1","my_ip_2"]
password_list=["passw_1","passw_2"]
#Start SSH
ssh = paramiko.client.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
# loop for IP and password
for i,n in zip(ip_list,password_list):
print(i,n)
try:
print("Open session in: " + i + "...")
ssh.connect(i, username='root', password=n)
except paramiko.SSHException:
print("Connection Failed")
quit()
# Upload file to /tmp/
print("Uploading file to " + str(i) + " in /tmp/...")
sftp = ssh.open_sftp()
sftp.put(local_path, remote_path)
try:
# Here something stucks
stdin, stdout, stderr = ssh.exec_command("sysupgrade /tmp/myfile.bin", timeout=30)
sysupgrade_response=stdout.readlines()
print(sysupgrade_response)
sftp.close()
ssh.close()
except paramiko.SSHException:
print("Continue with others IP in list...")
sftp.close()
ssh.close()
continue
sftp.close()
ssh.close()
print("\n\n***********************End execution***********************\n\n")
This is the errors I got:
Traceback (most recent call last):
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\channel.py", line 699,
in recv
out = self.in_buffer.read(nbytes, self.timeout)
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\buffered_pipe.py",
line 164, in read
raise PipeTimeout()
paramiko.buffered_pipe.PipeTimeout
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "C:\Users\Python Scripts\myscript.py", line 73, in <module>
sysupgrade_response=stdout.readlines()
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\file.py", line 349,
in readlines
line = self.readline()
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\file.py", line 291,
in readline
new_data = self._read(n)
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\channel.py", line 1361,
in _read
return self.channel.recv(size)
File "C:\Users\AppData\Roaming\Python\Python37\site-packages\paramiko\channel.py", line 701,
in recv
raise socket.timeout()
After the "sysupgrade" command, I would like to close the connection with the first ip in the list ( or handling some errors ) and go on with the for loop and connect to the second ip in the list.
Hope is clear enough
I assume that the sysupgrade restarts the machine or at least the SSH server or networking.
I would guess that if you execute sysupgrade in your SSH client, it will also lose the connection, won't it?

Python Socket Error Handling

I'm trying to write socket error handling (exactly err 111 - Connection Refused) but nothing is happening. Terminal print that Errno 111 occured but it's not doing anything with it:
import errno
try:
#do something
except socket.error, v:
errorcode=v[0]
if errorcode==errno.ECONNREFUSED:
print "Connection Refused"
else:
print("Running Application")
Traceback (most recent call last): File "Test.py",
line 20, in
s.connect((IP, PORT)) File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args) socket.error: [Errno 111] Connection refused
Nothing else printed :/
What am I doing wrong ?
I think you need to use v.args[0] to get the error code.

How to close socket after python fail?

First, I encountered sockets in Python and faced this problem: when some error in my python code occurs, for example some syntax error before conn.close() on the second script start port is in use. The script already finished, but the socket is still open, kind of like busy socket.
Here is an error just for example:
web#web-X501A1 /var/www $ cd /home/web/www/public/py
web#web-X501A1 ~/www/public/py $ python sockets.py
connected: ('127.0.0.1', 47168)
Traceback (most recent call last):
File "sockets.py", line 164, in <module>
data = re.find('(<onvif>.*<\/onvif>)')
AttributeError: 'module' object has no attribute 'find'
web#web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
File "sockets.py", line 154, in <module>
sock.bind(('', 9090))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
web#web-X501A1 ~/www/public/py $ python sockets.py
Traceback (most recent call last):
File "sockets.py", line 154, in <module>
sock.bind(('', 9090))
File "/usr/lib/python2.7/socket.py", line 224, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 98] Address already in use
Code:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.bind(('', 9090))
sock.listen(1)
conn, addr = sock.accept()
try:
print 'connected:', addr
buffer = ''
while True:
buffer += conn.recv(1024)
data = re.find('(<code>.*<\/code>)', buffer)
print data
exit();
if not data:
continue
conn.send(data.upper())
except Exception:
pass
finally:
conn.close()
Enclose the usage of the socket in a try/finally clause. Close the socket in the finally part. Perhaps handle the exception in an except part. Something similar to this:
try:
result = x / y
except ZeroDivisionError:
print "division by zero!"
else:
print "result is", result
finally:
print "executing finally clause"
The problem here is the dirty socket closing which occurs when the script crashes without the proper TCP connection shutdown sequence. Thankfully there's a simple solution which tells the kernel to ignore the fact the socket is already in use (the port it's bound to):
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
That's all, add that before the bind call and you're set. Debugging your other errors will be much simpler and less time consuming once that's done ;) See more in the docs https://docs.python.org/2/library/socket.html#socket.socket.setsockopt
If you use netstat -nutap you should notice that you connection seems like it's still up, on a state named TIME_WAIT.
That's part of TCP protocol, and according to wikipedia:
represents waiting for enough time to pass to be sure the remote TCP
received the acknowledgment of its connection termination request.
[According to RFC 793 a connection can stay in TIME-WAIT for a maximum
of four minutes known as a MSL (maximum segment lifetime).]
So, when you try to reconnect immediately to the same port, python complains that this port is still busy and cant be bound yet, saying:
socket.error: [Errno 98] Address already in use
See this old question, where it is asked how to avoid this waiting time.

Python socket (Socket Error Bad File Descriptor)

The following receiveFile() function reads a filename and file data from the socket and splits it using the delimiter $.
But I am unable to close the socket and a Bad file descriptor error is raised. If I comment out the self.server_socket.close() statement then there is no error but the socket is listening forever.
Code:-
def listen(self):
self.server_socket.listen(10)
while True:
client_socket, address = self.server_socket.accept()
print 'connected to', address
self.receiveFile(client_socket)
def receiveFile(self,sock):
data = sock.recv(1024)
data = data.split("$");
print 'filename', data[0]
f = open(data[0], "wb")
#data = sock.recv(1024)
print 'the data is', data[1]
f.write(data[1])
data = sock.recv(1024)
while (data):
f.write(data)
data=sock.recv(1024)
f.close()
self.server_socket.close()
print 'the data is', data
print "File Downloaded"
Traceback:-
Traceback (most recent call last):
File "server.py", line 45, in <module>
a = Server(1111)
File "server.py", line 15, in __init__
self.listen()
File "server.py", line 20, in listen
client_socket, address = self.server_socket.accept()
File "c:\Python27\lib\socket.py", line 202, in accept
sock, addr = self._sock.accept()
File "c:\Python27\lib\socket.py", line 170, in _dummy
raise error(EBADF, 'Bad file descriptor')
socket.error: [Errno 9] Bad file descriptor
You are closing the server's listening socket, and after that calling again accept() on it.
To finish receiving one file you should close client connection's socket (sock in function receiveFile).
in this code i am trying to shut down the server once file is received
What you'll need is something to break out of the while True loop when you want to shut down the server. A simple solution would be to exploit the exception generated when you close the server socket...
def listen(self):
self.server_socket.listen(10)
while True:
try:
client_socket, address = self.server_socket.accept()
except socket.error:
break
print 'connected to', address
self.receiveFile(client_socket)
print 'shutting down'

Categories