Sending an uptime to a remote server through SSH with the method pxssh I have this code that I'm putting into a library script.

The aim of the code is the following:


The method is to connect to a remote server and run uptime on the remote server. The uptime will be displayed on the host machine, to see for how long the server has been running.


The aim in a near future, is to uptime-check several servers and have the results of my program, on the running machine.

I put the the method under a main to not run it when the library is imported.

from pexpect import pxssh
import pexpect

# conn_up is a function for connecting to a remote server and doing an uptime.

def conn_up():
    try:
        s = pxssh.pxssh()
        hostname = '192.168.1.32'
        username = 'pi'
        s.login(hostname, username,ssh_key='/home/miaou/priv_keys')
        s.sendline('uptime')   # run a command
        s.prompt()             # match the prompt
        print(s.before.decode())        # print everything before the prompt.
    except pxssh.ExceptionPxssh as e:
        print("pxssh failed on login.")
        print(e)


if __name__ == '__main__':
    conn_up()


Currently I have only one method, conn_up().

But if I want to create additional methods to broaden the tools available for my administration, should I list them all of them under __name__ == '__main__' or is there a simpler way to call all the future methods all at once?
It sounds like the problem is not the code but how to package it up in a such a way that only functions that you want to call get called when you want to call them.

A part of the solution is as you have defined it ...

if __name__ == '__main__':
    conn_up()


... this would ensure that conn_up() gets called, but you could just treat conn_up as a constructor and pull all the code from it and put it in another function which you then call on demand.

From further discussion with you on discord it seems that the issue is also in part about extending this in the future so I would advise packaging this up in to a class that you might add functions to, then can add to your "if __name__ == '__main__':" block additional functions as you add them, or through some other logic in a new "onStart()" function or something.

There's a great post on this here ...

Hope this helps.