Connect to socket in infinate loop with python
Question: I have a ssh deamon running on my local machine. I want infinitely connect to
ssh deamon and echo received data. Here is my script.

    
    
    [azatuni@noc python-tests]$ cat test.py
    #!/usr/bin/python
    
    import socket
    s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    PORT = 22
    DESTIP = '127.0.0.1'
    
    while 1 == 1:
     s.connect((DESTIP, PORT))
     data = s.recv(1024)
     s.close()
     print data
    

But when I run script, recieves the following error. But wihout loop,
everything works fine.

    
    
    [azatuni@noc python-tests]$ ./test.py
    SSH-2.0-OpenSSH_5.3
    
    Traceback (most recent call last):
      File "./test.py", line 9, in <module>
        s.connect((DESTIP, PORT))
      File "<string>", line 1, in connect
      File "/usr/lib64/python2.6/socket.py", line 167, in _dummy
        raise error(EBADF, 'Bad file descriptor')
    socket.error: [Errno 9] Bad file descriptor
    

Thanks beforehand.


Answer: You need to create a new socket before connecting again. This will work for
your:

    
    
    #!/usr/bin/python 
    import socket  
    PORT = 22  
    DESTIP = '127.0.0.1'  
    while 1 == 1:  
     s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 
     s.connect((DESTIP, PORT))  
     data = s.recv(1024) 
     s.close()  
    
     print data  
    

Be aware that code you've posted has errors in it:

    
    
    data = s.recv(102SSH-2.0-OpenSSH_5.3  
    

