2

I have a python script on a machine.

I could run it from both ssh connection and the console of the machine.

Because the script changes some IP config stuff, I want to disconnect the ssh before doing the IP changing - that way the ssh won't hang and will be closed properly before the IP changes.

So - is there a way in python to check if the script is ran from ssh? and if so to close the ssh?

Mohammad Yusuf
  • 16,554
  • 10
  • 50
  • 78
Ofek Agmon
  • 5,040
  • 14
  • 57
  • 101
  • if you know the machine you're sshing to, you can check the hostname :) – Jean-François Fabre Jan 04 '17 at 15:39
  • if you close the ssh connection won't the python script stop or remain on the ssh machine? – depperm Jan 04 '17 at 15:40
  • Look at [this question](http://stackoverflow.com/questions/19762162/check-if-a-python-script-is-running-on-remote-machine) – Yevhen Kuzmovych Jan 04 '17 at 15:40
  • thanks for your answers. and is there a way to close all current ssh connections? regardless if I am working from a ssh or from the console. I want to terminate all ssh connections before changing the ip – Ofek Agmon Jan 04 '17 at 16:31

2 Answers2

0

I don't have a Linux machine, but tested on a Mac. If you issue a who am i command and see an IP address, you are on an ssh connection. If not, you are at the console. This answer is based on the following answer.

On the console:

$ who am i
hai      ttys000  Dec 23 13:00

On ssh connection:

$ who am i
hai      ttys001  Jan  4 07:41  (192.168.1.19)

With this information, it is a matter of running the command from Python and parse the output.

Update

Another method is to check for the presence of the environment variable SSH_CLIENT or SSH_TTY, according to the answer here.

Community
  • 1
  • 1
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
  • thanks for your answer. and is there a way to close all current ssh connections? regardless if I am working from a ssh or from the console. I want to terminate all ssh connections before changing the ip – Ofek Agmon Jan 04 '17 at 16:31
0

If you run the command pkill --signal HUP sshd. It should kill all ssh connections.

Then if you import os and use os.system() you could terminate all ssh connections from python.

import os 

os.system("pkill --signal HUP sshd")
RiveN
  • 2,595
  • 11
  • 13
  • 26