NAME
FSM::Basic - Finite state machine using HASH as state definitions
VERSION
Version 0.22
SYNOPSIS
A small finite state machine using a HASH data as description of the states Mainly used to create fake bash or fake telnet server in the purpose to mimic some CLI device interface (like SWITCH or ROUTER interface) Perhaps a little code snippet. The HASH is easily using a JSON file
use FSM::Basic;
my $fsm = FSM::Basic->new( \%states, 'accept' );
my $final = 0;
my $out;
foreach my $in ( @ins )
{
( $final, $out ) = $fsm->run( $in );
say $out;
last if $final;
}
SUBROUTINES/METHODS
new
my $fsm = FSM::Basic->new( \%states, 'accept' );
Create the FSM with the HASH ref as first paramter and the initial state as second parameter
The HASH is like this:
my %states = (
'accept' => {
'expect' => {
'default' => {
'final' => 0,
'matching' => 'prompt'
}
},
'not_matching' => 'accept',
'not_matching0' => 'close',
'not_matching_info_last' => '% Bad passwords
',
'output' => 'Password: ',
'repeat' => 2
},
'close' => {'final' => 1},
'prompt' => {
'expect' => {
'not_matching' => 'prompt',
'exit' => {
'matching' => 'close',
'final' => 0
},
'meminfo' => {'do' => 'do { local( @ARGV, $/ ) = "/proc/meminfo" ; <> }'},
'h(elp)?|\\?' => {
'output' => 'exit
meminfo
mem_usage
User> '
},
'mem_usage' => {'do' => 'my ( $tot,$avail) = (split /\\n/ ,do { local( @ARGV, $/ ) = "/proc/meminfo" ; <> })[0,2];$tot =~ s/\\D*//g; $avail =~ s/\\D*//g; sprintf "%0.2f%%\\n",(100*($tot-$avail)/$tot); '},
},
'not_matching_info' => '% Unknown command or computer name, or unable to find computer address',
'output' => 'User> '
}
);
The keys are the states name. "expect" contain a sub HASH where the keys are word or REGEX expected as input
- executable code:
-
"do" for perl code
"exec" for system code,
and 4 dedicated commands:
"cat" just reading the file content provided in parameter).
"catRAND" chose randomly one of the files provided in parameter space separated
"catWRAND" chose randomly (weighted) one of the files provided in parameter space separatedwith a : to separate the weight
e.g. 'catWRAND' => './t/test_cat.txt:1 ./t/test_cat1.txt:50', in this case the file ./t/test_cat1.txt get 50 more chance to be selected than file ./t/test_cat.txt
"catSEQ" read sequentialy the next files provided in parameter space separated if "catSEQ_idx" is defined, that file is used to keep the state. Otherwise , the state file is named used all the files name from "catSEQ" concatenated with a final '.tate'. All spaces are replaced by an underscore
It is possible to use a regex to allow optional commands
e.g. "h(elp)?|\\?": { "output": "default\nexit\ntimeoutA\n__PROMPT__" }
This json section match for 'h' 'help' or '?'
In the regex, the group capture could be used in the command parameter as a substitution
1st group is substituted by __1__
2nd group is substituted by __2__
.. e.g. for a ping
"ping (.*)" => {"exec" => "ping -c 3 __1__"},
The __1__ is substitued by the first parameter in the expected command
If you run the command "ping 127.0.0.1" the exec run the command "ping -c 3 127.0.0.1"
Other example:
"cat /tmp/test/((\\w)(\\d))": {
"cat": "/tmp/test/__3__"
}
If you call with "cat /tmp/test/a1 the cat read the file /tmp/test/1" (without the 'a' because the group 3 is matching a single digit after a single character
If you need to match all possible partial match for a word ( like "h, "he", "hel", "help" to match the "help" state) Use the extra tag "swapregex": "1"
This reverse the REGEX test
In normal case (no "swapregex" ) The state is check with
$in =~ /^$key$/
Where $in is the input from the run() function and $key is the state defined in the HASH
In case of "swapregex": "1" we use this
$key =~ /^$in/
e.g.
'expect' => {
'not_matching' => 'prompt',
'help' => {
'swapregex' => 1,
'output' => 'in enable',
'final' => 0
}
}
In this example me match "h, "he", "hel", "help"
It is possible to do a case insensitive matching with the special tag "caseinsensitive": "1"
e.g.
'other' => {
'output' => 'in other',
'caseinsensitive' => 1,
'final' => 0
}
in this example "other", "OTHER", "Other", "otheR" (and all other case alternate set) match the state "other"
- "not_matching" the state if the input is not matching the "expect" value (if missing stay in the same state)
It is perfectly possible to add extra tag not used by FSM::Basic for generic purpose. Check examples/fake_bash_ssh1.* Take a look at timout and timer usage In this example if destination IP from the SSH connection is available, the file IP.json is used as definition (with fallback to fake_bash1.pl)
run
my ( $final, $out ) = $fsm->run( $in );
Run the FSM with the input and return the expected output and an extra flag
EXAMPLE
use strict;
use feature qw( say );
use FSM::Basic;
use JSON;
use Term::ReadLine;
my %states = (
'accept' => {
'expect' => {
'default' => {
'final' => 0,
'matching' => 'prompt'
}
},
'not_matching' => 'accept',
'not_matching0' => 'close',
'not_matching_info_last' => '% Bad passwords
',
'output' => 'Password: ',
'repeat' => 2
},
'close' => {'final' => 1},
'prompt' => {
'expect' => {
'not_matching' => 'prompt',
'exit' => {
'matching' => 'close',
'final' => 0
},
"read" => {'cat' => 'file.txt'},
"read_random" => {'catRAND' => 'file1.txt file2.txt file3.txt'},
"read_seq" => {'catSEQ' => 'file1.txt file2.txt file3.txt', 'catSEQ_idx' => 'catSEQ_status'},
'meminfo' => {'do' => 'do { local( @ARGV, $/ ) = "/proc/meminfo" ; <> }'},
'mem' => {
'do' => "my ( $tot,$avail) = (split /\n/ ,do { local( @ARGV, $/ ) = \"/proc/meminfo\" ; <> })[0,2];$tot =~ s/\\D*//g; $avail =~ s/\\D*//g; sprintf \"%0.2f%%\\n\",(100*($tot-$avail)/$tot);"
},
'h(elp)?|\\?' => {
'output' => 'exit
read
read_random
read_seq
meminfo
mem_usage
mem
User> '
},
'mem_usage' => {'do' => 'my ( $tot,$avail) = (split /\\n/ ,do { local( @ARGV, $/ ) = "/proc/meminfo" ; <> })[0,2];$tot =~ s/\\D*//g; $avail =~ s/\\D*//g; sprintf "%0.2f%%\\n",(100*($tot-$avail)/$tot); '},
},
'not_matching_info' => '% Unknown command or computer name, or unable to find computer address',
'output' => 'User> '
}
);
my $history_file = glob( '/tmp/fsm.history' );
my $prompt = '> ';
my $line;
my $final = 0;
my $term = new Term::ReadLine 'bash';
my $attribs = $term->Attribs->ornaments( 0 );
$term->using_history();
$term->read_history( $history_file );
$term->clear_signals();
my $fsm = FSM::Basic->new( \%states, 'accept' );
my $out = "Password> ";
while ( defined( $line = $term->readline( $out ) ) )
{
( $final, $out ) = $fsm->run( $line );
$term->write_history( $history_file );
last if $final;
}
print $out if $final;
More sample code in the examples folder.
TODO
add "edit" to allow on the fly modification of the states definition
add "verify_states" to check all states are reachable from a original state
SEE ALSO
FSA::Rules
https://metacpan.org/pod/FSA::Rules
AUTHOR
DULAUNOY Fabrice, <fabrice at dulaunoy.com>
BUGS
Please report any bugs or feature requests to bug-FSM-basic at rt.cpan.org
, or through the web interface at http://rt.cpan.org/NoAuth/ReportBug.html?Queue=FSM-Basic. I will be notified, and then you'll automatically be notified of progress on your bug as I make changes.
SUPPORT
You can find documentation for this module with the perldoc command.
perldoc FSM::Basic
You can also look for information at:
RT: CPAN's request tracker (report bugs here)
AnnoCPAN: Annotated CPAN documentation
CPAN Ratings
Search CPAN
ACKNOWLEDGEMENTS
LICENSE AND COPYRIGHT
Copyright 2008 - 2020 DULAUNOY Fabrice.
This program is free software; you can redistribute it and/or modify it under the terms of the the Artistic License (2.0). You may obtain a copy of the full license at:
http://www.perlfoundation.org/artistic_license_2_0
Any use, modification, and distribution of the Standard or Modified Versions is governed by this Artistic License. By using, modifying or distributing the Package, you accept this license. Do not use, modify, or distribute the Package, if you do not accept this license.
If your Modified Version has been derived from a Modified Version made by someone other than you, you are nevertheless required to ensure that your Modified Version complies with the requirements of this license.
This license does not grant you the right to use any trademark, service mark, tradename, or logo of the Copyright Holder.
This license includes the non-exclusive, worldwide, free-of-charge patent license to make, have made, use, offer to sell, sell, import and otherwise transfer the Package with respect to any patent claims licensable by the Copyright Holder that are necessarily infringed by the Package. If you institute patent litigation (including a cross-claim or counterclaim) against any party alleging that the Package constitutes direct or contributory patent infringement, then this Artistic License to you shall terminate on the date that such litigation is filed.
Disclaimer of Warranty: THE PACKAGE IS PROVIDED BY THE COPYRIGHT HOLDER AND CONTRIBUTORS "AS IS' AND WITHOUT ANY EXPRESS OR IMPLIED WARRANTIES. THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR NON-INFRINGEMENT ARE DISCLAIMED TO THE EXTENT PERMITTED BY YOUR LOCAL LAW. UNLESS REQUIRED BY LAW, NO COPYRIGHT HOLDER OR CONTRIBUTOR WILL BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING IN ANY WAY OUT OF THE USE OF THE PACKAGE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.