4

I'm new to Python. Currently I'm using it to connect to remote servers via ssh, do some stuff (including copying files), then close the session.

After each session I do ssh.close() and sftp.close(). I'm just doing this because that's the typical way I found on the internet.

I'm wondering what would happen if I just finishes my script without closing the session. Will that affect the server? Will this make some kind of (or even very little) load on the server? I mean why we are doing this in the first place?

KhaledMaged
  • 449
  • 1
  • 5
  • 12

2 Answers2

5

The (local) operating system closes any pending TCP/IP connection opened by the process, when the process closes (even if it merely crashes).

So in the end the SSH session is closed, even if you do not close it. Obviously, it's closed abruptly, without proper SSH cleanup. So it may trigger some warning in the server log.

Closing the session is particularly important, when the process is long running, but the session itself is used only shortly.

Anyway, it's a good practice to close the session no matter what.

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
3

We close session after use so that the clean up(closing of all running processes associated to it) is done correctly/easily.

When you ssh.close() it generates a SIGHUP signal. This signal kills all the tasks/processes under the terminal automatically/instantly.

When you abruptly end the session that is without the close(), the OS eventually gets to know that the connection is lost/disconnected and initiates the same SIGHUP signal which closes most open processes/sub-processes.

Even with all that there are possible issues like few processes continue running even after SIGHUP because they were started with a nohup option(or have somehow been disassociated from the current session).

Ani Menon
  • 27,209
  • 16
  • 105
  • 126