开发者

Creating a simple command line interface (CLI) using a python server (TCP sock) and few scripts

开发者 https://www.devze.com 2022-12-28 20:29 出处:网络
I have a Linux box and I want to be able to telnet into it (port 77557) and run few required commands without having to access to the whole Linux box. So, I have a server listening on that port, and e

I have a Linux box and I want to be able to telnet into it (port 77557) and run few required commands without having to access to the whole Linux box. So, I have a server listening on that port, and echos the entered command on the screen. (for now)

Telnet 192.168.1.100 77557

Trying 192.168.1.100...

Connected to 192.168.1.100.

Escape character is '^]'.

hello<br />

You typed: "hello"<br />

NOW:

I want to create lot of commands that each take some args and have error codes. Anyone has done this before? It would be great if I can have the server upon initialization go through each directory and execute the init.py file and in turn, the init.py file of each command call into a main template lib API (e.g. RegisterMe()) and register themselves with the server as function call backs. At least this is how I would do it in C/C++.

But I want the best Pythonic way of doing this.

/cmd/

/cmd/myreboot/

/cmd/myreboot/ini.py (note underscore don't show for some reason)

/cmd/mylist/

/cmd/mylist/init.py

... etc

IN: /cmd/myreboot/__ini__.py:

from myMainCommand import RegisterMe

RegisterMe(name="reboot",args=Arglist, usage="Use this to reboot the box", desc="blabla")

So, repeating this creates a list of commands and when you enter the command in the telnet session, then the server goes through the list, matches开发者_运维百科 the command and passed the args to that command and the command does the job and print the success or failure to stdout.

Thx


I would build this app using combination of cmd2 and RPyC modules.


Twisted's web server does something kinda-sorta like what you're looking to do. The general approach used is to have a loadable python file define an object of a specific name in the loaded module's global namespace. Upon loading the module, the server checks for this object, makes sure that it derives from the proper type (and hence has the needed interface) then uses it to handle the requested URL. In your case, the same approach would probably work pretty well.

Upon seeing a command name, import the module on the fly (check the built-in import function's documentation for how to do this), look for an instance of "command", and then use it to parse your argument list, do the processing, and return the result code.

There likely wouldn't be much need to pre-process the directory on startup though you certainly could do this if you prefer it to on-the-fly loading.

0

精彩评论

暂无评论...
验证码 换一张
取 消