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

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.

Related

How to run powershell script remotely using chef?

I have powershell script which is present on chef server to run on remote windows server, how can i run this powershell script from chef server on remote windows server.
Chef doesn't do anything like this. First, Chef Server can never remotely access servers directly, all it does is stores data. Second, Chef doesn't really do "run a thing in a place right now". We offer workstation tools like knife ssh and knife winrm as simplistic wrappers but they aren't made for anything complex. The Chef-y way to do this would be to make a recipe and run your script using the the powershell_script resource.
Does it mean chef is also running on Windows server ?
If yes, why not to use psexec from Windows Ps tools ?
https://learn.microsoft.com/en-us/sysinternals/downloads/psexec
Here is my understanding of what you are trying to achieve. If I'm wrong then please correct me in a comment and I will update my answer.
You have a powershell script that you need to run on a specific server or set of servers.
It would be convenient to have a central management solution for running this script instead of logging into each server and running it manually.
Ergo you either need to run this script in many places when a condition isn't filled, such as a file is missing, or you need to run this script often, or you need this script to be run with a certain timing in regards to other processes you have going on.
Without knowing precisely what you're trying to achieve with your script the best solution I know of is to write a cookbook and do one of the following
If your script is complex place it in your cookbook/files folder (assuming the script will be identical on all computers it runs on) or in your cookbook/templates folder (if you will need to inject information into it at write time). You can then write the .ps file to the local computer during a Chef converge with the following code snippet. After you write it to disk you will also have to call it with one of the commands in the next bullet.
Monomorphic file:
cookbook_file '<destination>' do
source '<filename.ps>'
<other options>
end
Options can be found at https://docs.chef.io/resource_cookbook_file.html
Polymorphic file:
template '<destination>' do
source '<template.ps.erb>'
variables {<hash of variables and values>}
<other options>
end
Options can be found at https://docs.chef.io/resource_template.html
If your script is a simple one-liner you can instead use powershell_script, powershell_out! or execute. powershell_out! has all the same options and features as the shell_out! command and the added advantage that your converge will pause until it receives an exit status for the command, if that is desirable. The documentation on using it is a bit more spotty though so spend time experimenting with it and googling.
https://docs.chef.io/resource_powershell_script.html
https://docs.chef.io/resource_execute.html
Which ever option you end up going with you will probably want to guard your resource with conditions on when it should not run, such as when a file already exists, a registry key is set or what ever else your script changes that you can use. If you truly want the script to execute every single converge then you can skip this step, but that is a code smell and I urge you to reconsider your plans.
https://docs.chef.io/resource_common.html#guards
It's important to note that this is not an exhaustive list of how to run a powershell script on your nodes, just a collection of common patterns I've seen.
Hope this helped.

How to handle interactive commands in Perl?

I have a perl script which calls a command which before executing asks for confirmation. How do I handle this in Perl?
For example let say in my perl script I am doing the following
`ssh myServer`;
Before connecting I get a prompt asking to proceed or not. I have to provide yes as my next command. How can I achieve this? Any code snippet would be useful.
If you are looking at interactive you can use Expect on the CPAN...
"Expect is a generic tool for talking to processes that normally require
user interaction. This might be running an ftp client to grab a file,
telnetting to a router to grab statistics or reset an interface. Or, as in the
case of a place I recently administered, to start up a secure webserver without
having to be physically at the machine to enter the super secret password."
However, there are other (better) methods to automate SSH login. I.e. by using ssh-keygen
From Net::SSH :
interactive
Set to a true value if you're using Net::SSH::Perl interactively. This is used in determining whether or not to display password prompts, for example. It's basically the inverse of the BatchMode parameter in ssh configuration.
Defaults to false.

Spawn external process from a CGI script

I've searched and found several very similar questions to mine but nothing in those answers have worked for me yet.
I have a perl CGI script that accepts a file upload. It looks at the file and determines how it should be processed and then calls a second non-CGI script to do the actual processing. At least, that's how it should work.
This is running on Windows with Apache 2.0.59 and ActiveState Perl 5.8.8. The file uploading part works fine but I can't seem to get the upload.cgi script to run the second script that does the actual processing. The second script doesn't communicate in any way with the user that sent the file (other than it sends an email when it's done). I want the CGI script to run the second script (in a separate process) and then 'go away'.
So far I've tried exec, system (passing a 1 as the first parameter), system (without using 1 as first parameter and calling 'start'), and Win32::Process. Using system with 1 as the first parameter gave me errors in the Apache log:
'1' is not recognized as an internal or external command,\r, referer: http://my.server.com/cgi-bin/upload.cgi
Nothing else has given me any errors but they just don't seem to work. The second script logs a message to the Windows event log as one of the first things it does. No log entry is being created.
It works fine on my local machine under Omni webserver but not on the actual server machine running Apache. Is there an Apache config that could be affecting this? The upload.cgi script resides in the d:\wwwroot\test\cgi-bin dir but the other script is elsewhere on the same machine (d:\wwwroot\scripts).
There may be a security related problem, but it should be apparent in the logs.
This won't exactly answer your question but it may give you other implementation ideas where you will not face with potential security and performance problems.
I don't quite like mixing my web server environment with system() calls. Instead, I create an application server (with POE usually) which accepts the relevant parameters from the web server, processes the job, and notifies the web server upon completion. (well, the notification part may not be straightforward but that's another topic.)

PHP Slow to process soap request via browser but fine on the command line

I am trying to connect to an external SOAP service using PHP and have written a small php test script that just connects to the service and performs a simple request to check everything is working.
This all works correctly but when I run via a browser request, it is very slow taking somewhere in the region of 40s to establish the initial connection. When I do the same request using the exact same script on the command line, it goes through straight away.
Does anyone have any ideas as to why this might be?
Cheers
PHP caches the wsdl in /tmp. If you run from the command line first, the cache file will be owned by whatever user you're running the script as, and apache won't be able to read the cache. The wsdl will have to be downloaded and parsed every time which will be slow.
Check the permissions of /tmp/wsdl*.
Maybe external SOAP service trying to check your IP, and your server has ICMP allowed, when your local network - not.
Anyway, this question might be answered more clearly by administrator of external SOAP service :)
Is there a difference between the php.inis that are being used?
On a standard ubuntu server installation:
diff /etc/php5/apache2/php.ini /etc/php5/cli/php.ini
//edit:
Another difference might be in the include paths. Had this trouble myself on a local test server, it didn't actually use the soap class that was included (it didn't include anything, because the search paths weren't valid), but it included the built-in soap_client class.

How to improve workflow for creating a Lua-based Wireshark dissector

I've finally created a Dissector for my UDP protocol in Lua for Wireshark, but the work flow is just horrendous. It consists of editing my custom Lua file in my editor, then double-clicking my example capture file to launch Wireshark to see the changes. If there was an error, Wireshark informs me via dialogs or a red line in the Tree analysis sub-pane. I then re-edit my custom Lua file and then close that Wireshark instance, then double-click my example capture file again. It's like compiling a C file and only seeing one compiler error at a time.
Is there a better (faster) way of looking at my changes, without having to restart Wireshark all the time?
At the time, I was using Wireshark 1.2.9 for Windows with Lua enabled.
The best way to automate this is by using command line. Yep, use tshark instead of loading gui thingy.
If your lua script is called "proto.lua" and it defines an protocol called "MyProto" that uses port 8888, you can test your dissector using:
tshark -X lua_script:proto.lua -O MyProto -V -f "port 8888"
-V option makes tshark print all the info of all protocols.
-O option filters the -V option to make it show all the info only on the listed(CSV) protocols.
-f option filters all packets that doesn't conform to the rule. In this case any packet that is not from the right port.
The latest Wireshark release comes with a primitive console for running lua script. It can be found under Tools -> Lua -> Evaluate. From there, you should be able to reload your dissector by running dofile(). You'll also have to remove the previous version of your dissector.
Here's an example for a TCP-based dissector.
local tcp_dissector_table = DissectorTable.get("tcp.port")
tcp_dissector_table:remove(pattern, yourdissector)
yourdissector = nil
dofile("c:/path/to/dissector.lua")
I recommend placing this code in a function inside your file.
Now there's a problem with this answer: If your script created a Proto object, it seems that you can't create it again with the same id. The constructor for the Proto class calls the C function proto_register_protocol() (see epan/wslua/wslua_proto.c). I can't find any lua function that will unregister the protocol. In fact, I can't even find a C function to unregister it.
You might be able to write a trivial wrapper function that Wireshark loads, and have it just load the real file from disk (e.g. via dofile()). This could probably "trick" Wireshark into always reloading your Lua code until you're more comfortable with it and can remove this hack.
I've been facing the same problem for quite a while, so I have decided to create a tool that would help me streamline that "horrendous workflow". The tool in question is Wirebait. It is designed to let you run your Lua dissectors as you write them without Wireshark.
It is very quick and easy to install and use. All you have to do is load the Wirebait module and add a five liner snippet on top of your dissector script. Then if you use an IDE such as ZeroBrane Studio, Wirebait allows you to literally write and debug your code on the fly, no need for wireshark. If you don't even have a pcap file, you can use a hexadecimal string representing the data you want to dissect.