Why is exit() or exec needed after telnetlib read_all()
<p>A lot of resources, including the example in the official documentation at <a href="https://docs.python.org/2/library/telnetlib.html" rel="nofollow">telnetlib</a> suggest that at the end before you do a read_all(), you need to write exit after the command as: </p>

<pre><code>tn.write("ls\n")
tn.write("exit\n")
</code></pre>

<p>Can someone please help me understand why is this needed ?</p>

<p>If I try doing it without the exit, the telnet connection hangs (or at least looks like it is hung) as the output of the command executed does  not show on the terminal. </p>

<p>Also, another way of making it work, as I found in some resources was to use 'exec' to fire up the command and then you don't need the exit thing anymore. </p>

<p>Please help me understand this as well. </p>

<p>read_all() reads all the output until EOF. In other words, it waits until remote server closes connection and returns you all the data it has sent. If you have not previously notified the server with an "exit" command that you have no more commands for it, it will wait for them. And a deadlock occurs: you are holding open connection because you are waiting for server to tell you that it has sent everything it intended to say, and server waits for new orders from you and is ready to add more data to it's output.</p>

python exec telnet exit telnetlib