NAME

Sys::Manage::Conn - Connection to remote Perl

SYNOPSIS

Script
  use Sys::Manage::Conn;
  my $s =Sys::Manage::Conn->new([@ARGV], -option=>value,...)->connect();

  $s->reval('print "Hello World,"\\n";');
  $s->rcmd('dir');
  $s->reval(['cd'], ';print "Hello World,"\\n";');
  $s->reval('print "Hello World,"\\n";', ['logname']);
  print $s->rfread('/etc/passwd');
  $s->rfget('c:\\autoexec.sys', $s->{-tmp} .'.txt');
  $s->rdo('/my/files/script.pl');
Command line utility
  #!perl -w
  use Sys::Manage::Conn;
  my $s =Sys::Manage::Conn->connect([@ARGV], -exec=>1, -option=>value,...);
  exit($?>>8);

  script 0 rcmd         dir
  script 0 fget         /etc/passwd     /secure/passwd
  script 0 fget -p      /etc            /secure/etc
  script 0 rdo          /my/files/script.pl
  script 0 rdo  -p      "%HOME%\packages\package.zip\start.bat"
Command line
  script -vde node:port user:password other-args

  (all command line arguments are optional, at least first will be 'node' or 0)

        -v              verbose mode, from 'v1' to 'v3'
        -d              debug mode (step-by-step execution)
        -e              execute rest of command line
        node            remote computer name or tcp/ip address, 0 for local
        port            remote computer IO::Socket::INET server port
        user            user name on remote computer
        password        password to login

        other-args (using '-e' or '-exec=>1'; '?' - optional):

                rcmd    ?-'o-e-         os-command      argumets-list
                lcmd    ?-              os-command      argumets-list
                rdo     ?-o-e-p         ?os-command !   local-script    ?args
                fget    ?-'mp           remote-source   local-target
                mget    ?-'mr           remote-dir      local-dir       mask    ?seconds
                fput    ?-'mp           local-source    remote-target
                mput    ?-'mr           local-dir       remote-dir      mask    ?seconds
                agtfile ?-l             agent-script

                where:
                        -'      quote remote arg with "'"
                        -o-     refuse STDOUT
                        -e-     refuse STDERR
                        -m      move file(s)
                        -p, -z  pack file(s)
                        -r      recurse subdirectories
                        -l      loop agent script

DESCRIPTION

This module starts on remote computer Perl command line implementing IO::Socket::INET server to accept Perl source strings and return results. This may be considered as an agent implementation within Perl command line. The source may be seen using -v3 option or -echo=3.

There may be various methods to start Perl command line mentioned and corresponding -init and -perl values. Default is 'wmi' for Windows and 'rsh' otherwise.

The security is only tcp/ip address of manager, -chkip value with default.

This module is implemented and tested with Perl 5.6.0 on Windows 2000.

ABOUT REMOTE AGENT CONSTRUCTIONS

    There may be a several variants.

    Agent as a Perl Command Line

    This variant is currently implemented.

    Agent is a Perl command line (about 300 bytes) started via some remote command service:

      perl -e "use IO::Socket;$r_=IO::Socket::INET->new(LocalPort=>8008,Reuse=>1,Listen=>1);$m_=$r_->accept();$r_->close;die if $m_->peerhost ne '127.0.0.1';while(defined($r_=$m_->getline)){$@=undef;$r_=eval $r_;$m_->printflush(\"\n----ret\$?\$!\$\@: $?\t$!\t$^E\t$@\t$r_\n\")}"

    Additional agent code may be added to the first command evaluation.

    Advantages: lite agent, lite load.

    Disadvantages: agent size limitation.

    Agent loader as a Perl Command Line

    Agent will be loaded via a Perl command line (about 200 bytes) started via some remote command service:

      perl -e "use IO::Socket;$r_=IO::Socket::INET->new(LocalPort=>8008,Reuse=>1,Listen=>1);$m_=$r_->accept();$r_->close;do eval $m_->getline if $m_->peerhost ne '127.0.0.1'"

    The first row transferred will be an agent loader, it should accept entire agent code and store it into temporary file.

    Advantages: agent may be more complex.

    Disadvantages: increased agent startup load.

    Separate Agent

    Agent is a script file to be distributed and started on computers.

    Advantages: agent may be very complex.

    Disadvantages: agent distribution and manager authorization should be implemented, at least manager's IP address should be considered.

    Note: agtfile method below produces a simple separate agent file may be used with -init => ''.

SLOTS

SLOTS

The usually slots are -init, -node, -user, -echo and -debug, -argv.

-agent
$m_
        => IO::Socket::INET

Connection to remote agent. Established by connect. Used internally.

Evaluated on remote agent code may use $m_ variable.

-argv
        => [rest of @ARGV unparsed]

Command line arguments for script itself. Parsing set([@ARGV]), some arguments first may be found for module, but arguments rest may be for script only. So, script may access it's own arguments via {-argv}->[arg number].

-cfg
-config
        => false | true | filename

Instruction to load configuration file. Default file name is 'Sys-Manage-Conn-cfg.pl'. It will be searched alike Sys::Manage::Cmd configuration file. $_ will contain object to be configured.

-chkip
        => gethostbyname | ''

TCP/IP address of manager (local node or host). Default value is given using gethostbyname (Sys::Hostname or Win32::NodeName).

-debug
        => false | true
-d

Debug mode. Automatically sets -echo=3.

-dirm
        => directory marker sign

Directory marker, '/' or '\', filled automatically using $0 or $^O.

-dirw
        => working directory

Directory where script started. Obtained using Cwd or Win32::GetCwd.

-echo
-v
        => 0 | 1 | 2 | 3

Echo printout level, verbosity level.

0 - none.

1 - print commands invoking alike rcmd or reval.

2 - print remote stdout and stderr accepting

3 - print perl sources transfer

See also -debug, -progress.

-errchild
        => remote $?
-errexit
        => remote $?>>8
-erros
        => remote $!
-erros1
        => remote $^E
-erreval
        => remote $@

Errors from perl source remotely evaluated. Accepted via getret, where also local $? and $@ are filled from -errchild and -erreval.

See also -reteval.

-error
        => 'die' | 'warn' | false

Error or exception processing behaviour.

-exec
-e
        => false | true

Execute -argv within -connect. The first argument may be a method name (rcmd, reval, fput, fget,...). Default considered as rcmd.

-init
        => 'wmi' | 'rsh' | 'telnet' | sub{}(self, agent command line) || ''

Remote agent initiation method. WMI ('wmi') is default for Windows, 'rsh' otherwise. Empty agent initiation may be used with separate agent may be written. See also -perl.

-mark
        => '----ret$?$!$@: '

Command output end marker. Used by getret to finish -agent reading. Output of the remote execution should not contain -mark value.

-node
        => remote node

Remote computer name or TCP/IP address to connect to. See also -port.

-pack
        => 'zip' | 'arj' | 'tar'
-packx
        => undef | 'unzip' |...

Filesystem packer and unpacker used to provide -p+. There may be a full path to call utility.

-perl
        => 'perl'

Discoverable file name of remote Perl interpreter. Default is 'perl', rely on $ENV{path}.

-prgcn
        => f($0)
-prgfn
        => f($0)

Common and full names of script, filled automatically using $0. Common name is used in -tmp value.

-progress
        => true | false

Output progress with -echo.

-pswd
        => false | password string

Password to login -user to -node during connect. Default behaviour tries without password

-port
        => 8008

Remote agent TCP/IP port number to listen by IO::Socket::INET. See also -node.

-reject
        => undef | sub{}(self, method, options, argument,...) -> reject message

Commands reject condition. May be useful supplying Sys::Manage::Cmd service to suboperators.

$ENV{SMCFP}, $ENV{SMELEM}, $ENV{SMLIB} may be mentioned in conditions.

See also Sys::Manage::Cmd -reject.

-retbps
        => 0 || bytes per seconds

Data transfer speed, the last determined by fget or fput value. Used in time limit conditions, i.e. in mget and mput.

-retexc
        => false || true

Mark of excess achieved, i.e. time limit in mget or mput.

-reteval
        => value or data structure

Result of evaluation of remote Perl source accepted by getret. Result of last reval.

-tmp
$t_
        => temporary file name

Temporary file name. Filled using $ENV{TEMP} or $ENV{tmp}, -dirm, -prgcn. May be used to construct name of temporary file or directory.

Evaluated on remote agent code may use $t_ variable.

-timeout
        => undef

Network operations timeout.

-title
        => 'Remote command stream'

Title to display sometimes...

-user
        => false | user name

Remote user name to login to -node inside connect. -pswd also may be required. Default is current user.

-wmi
        => undef | WMI object

Windows WMI Win32::OLE connection, if opened by connect.

-wmisil
        => undef | 4 | 3 | [4,3]

Windows WMI security impersonation level(s) to use. See MSDN 'Platform SDK: Windows Management Instrumentation'.

4 - delegate. Allows objects to permit other objects to use the credentials of the caller. Windows 2000 and later. In 'Active Directory Users and Computers' the account of Agent computer must be marked as 'Trusted for delegation' and the account of Manager computer must not be marked as 'Account is sensitive and cannot be delegated'. Manager computer, agent computer and the domain controller must be members of the same domain or in trusted domains. See MSDN 'Connecting to a 3rd Computer-Delegation'.

3 - impersonate. Allows objects to use the credentials of the caller. Recommended in MSDN for Scripting API for WMI calls. See MSDN 'Setting the Default Process Security Level Using VBScript'.

[4,3] - start with 4 and decrease to 3 if security error.

undef - default encoded in connect, 3 without password, [4,3] with password, alike some Windows utilities behaviour.

-wmisis
        => undef | 1

Start agent as a Windows service using 'System' account and interacting with desktop.

Ignored for agent computers without 'Win32_Service' WMI class.

To allow access from agent to network shares on file server special Registry parameters may be required (see in Microsoft Technet):

        'HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\LanmanServer\Parameters\NullSessionShares' (REG_MULTI_SZ) = share-names
        'HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\LSA\RestrictAnonymous' (REG_DWORD) = 0

connect automatically installs service 'Sys-Manage--chkip.pl' if it is not already exists. Required files are written to '$ENV{SystemRoot}\System32' directory during installation:

        'instsrv.exe' and 'srvany.exe' Windows Resource Kit utilities, if not already exists.
        'Sys-Manage*.pl' agent script.

METHODS

METHODS

The main methods are new, connect, reval, rcmd, fput, fget, rdo.

agtfile (?-options, target file) -> success

Writes separate agent script file to be used with -init => ''.

Used METHOD CALL OPTIONS: -', -l.

connect (-option=>value,...) -> self
connect ([command line arguments], -option=>value,...) -> self
connect ('class', [command line arguments], -option=>value,...) -> new object

Connects to remote -node, using -init, -user, -pswd. Starts remote -perl with command line IO::Socket::INET agent on -port, connects -agent to it.

disconnect () -> self

Closes connection opened.

error (error message) -> error value

Proceeds error according to -error. Returns undef, if returns.

fget (?-options, remote file name, local file name) -> success
rfget (?-options, remote file name, local file name) -> success

Reads remote file and writes it locally.

Used METHOD CALL OPTIONS: -', -m, -b-, -s+, -p+.

Default REMOTE SOURCE EXPANSION: do{.

See also rfread.

fput (?-options, local file name, remote file name) -> success
rfput (?-options, local file name, remote file name) -> success

Reads local file and writes it remotely.

Used METHOD CALL OPTIONS: -', -m, -b-, -s+, -p+.

Default REMOTE SOURCE EXPANSION: do{.

With -p+ option, archiver will not be used if local file is already packed.

See also rfwrite.

isscript ('lib name') -> exists?

Checks if $0 is from library specified, alike Sys::Manage::Cmd::isscript, uses $ENV{SMDIR} and $ENV{SMLIB}. Useful for -reject.

lcmd (?-options, command and arguments, ?filter sub{}) -> success

Locally executes command given. Command and arguments will be (re)quoted automatically, but single command will not be (re)quoted to allow rich shell command lines.

lfread (?-options, local file name) -> content

Reads local file and returns it's content.

Used METHOD CALL OPTIONS: -b-.

See also rfread, lfwrite.

lfwrite (?-options, local file name, content) -> success

Writes to local file content given.

Used METHOD CALL OPTIONS: -b-.

See also rfwrite, lfread.

lls (?-options, path, ?filter, ?attr get, ?container''[]{}) -> list || success

Lists local directory. Returns list or container given, undefined on error. Container may be string, hash ref, array ref. Additional directory entry attributes may be get using 'sub{}(path,$_=name,file)' or 'expr'. Directory entries may be filtered using 'sub{}(path,name,$_=file)' or 'mask'. Path may be evaluated using 'sub{}' or 'do{}'.

See also rls.

mget (?-options, remote dir, local dir, ?filter, ?time limit, ?approve sub{}(self,opt,file,file) -> success, ?all done sub{}(self,opt,dir,dir) | method, args) -> success

Replicates multiple remote files to local side. Directory entries may be filtered using 'sub{}(path,name,$_=file)' or filemask syntax. Limit of time to spend may be specified in seconds, $ENV{SMSECS} will be also considered.

Used METHOD CALL OPTIONS: -', -m, -r.

Return codes: 1 - done partial (up to time limit), 2 - done all, 3 - nothing todo.

See also fget, mput.

Examples:

$s->mget('C:\\tmp', 'c:\\tmp\\1', 'sub{/\\.(doc|ppt)/}');

$s->mget('C:\\tmp', 'c:\\tmp\\1', 'sub{/\\.(doc|ppt)/}', 'lcmd', 'cmd', '/c', 'dir', 'c:\\tmp\\1');

$s->mget('C:\\tmp', 'c:\\tmp\\1', 'sub{/\\.(doc|ppt)/}', 10, sub{print $_[2],"\n"}, 'lcmd', 'cmd', '/c', 'dir', 'c:\\tmp\\1');

mput (?-options, local dir, remote dir, ?filter, ?time limit, ?approve sub{}(self,opt,file,file) -> success, ?all done sub{}(self,opt,dir,dir) | method, args) -> success

Replicates multiple local files to remote side. Directory entries may be filtered using 'sub{}(path,name,$_=file)' or filemask syntax. Limit of time to spend may be specified in seconds, $ENV{SMSECS} will be also considered.

Used METHOD CALL OPTIONS: -', -m, -r.

Return codes: 1 - done partial (up to time limit), 2 - done all, 3 - nothing todo.

See also fput, mget.

Examples:

$s->mput('C:\\tmp','c:\\tmp\\1','sub{/\\.(doc|ppt)/}');

$s->mput('C:\\tmp', 'c:\\tmp\\1', 'sub{/\\.(doc|ppt)/}', 10, 'rcmd', 'cmd', '/c', 'dir', 'c:\\tmp\\1');

$s->mput('C:\\tmp', 'c:\\tmp\\1', 'sub{/\\.(doc|ppt)/}', 10, sub{print $_[2],"\n"}, 'rcmd', 'cmd', '/c', 'dir', 'c:\\tmp\\1');

new ('class', -option=>value,...) -> new object
new ('class', [command line arguments], -option=>value,...) -> new object

Creates new Sys::Manage::Conn object. See also set syntax.

rcmd (?-options, command and arguments, ?filter sub{}) -> success

Remotely executes command given. Command and arguments will be (re)quoted automatically, but single command will not be (re)quoted to allow rich shell command lines.

Used METHOD CALL OPTIONS: -', -o-, -e-.

Default REMOTE SOURCE EXPANSION: do{.

rdo (?-options, local file, ?arguments,.., ?filter sub{}) -> result
rdo (?-options, interpreter call, '!', local file, ?arguments,.., ?filter sub{}) -> result

Transfers local file to temporary remote file, executes and unlinks it, returns result of execution. Command line arguments will be quoted automatically. Result is considered as return value of Perl do or !($?>>8).

'!' is default separator between optional interpreter command line and file to be executed, see -e!. Default interpreter associations may be found in the source code. General default is Perl script via do "filename".

Used METHOD CALL OPTIONS: -o-, -e-, -e!, -p+.

With -p+ option, the whole directory of command file will be packed and transferred into temporary directory. As fput used, this directory will not be packed if it is packed file already, i.e. 'rdo packedFile.zip/scriptFile.pl'

reval (?-options, perl source strings, ?filter sub{}) -> result

Remotely evaluates Perl source given. Returns result transferred using Data::Dumper.

Used METHOD CALL OPTIONS: -o-, -e-.

Default REMOTE SOURCE EXPANSION: system(.

rfread (?-options, remote file name) -> content

Reads remote file and returns it's content.

Used METHOD CALL OPTIONS: -', -b-.

Default REMOTE SOURCE EXPANSION: do{.

See also lfread, rfget, rfwrite.

rfwrite (?-options, remote file name, content) -> success

Writes to remote file content given.

Used METHOD CALL OPTIONS: -', -b-.

Default REMOTE SOURCE EXPANSION: do{.

See also lfwrite, rfput, rfread.

rls (?-options, remote path, ?filter, ?attr get, ?container''[]{}) -> list || success

Lists remote directory. Returns list or container given, undefined on error. Container may be string, hash ref, array ref. Additional directory entry attributes may be get using 'sub{}(path,$_=name,file)' or 'expr'. Directory entries may be filtered using 'sub{}(path,name,$_=file)' or 'mask'. Remote path may be evaluated using 'sub{}' or 'do{}'.

Example: $s->rls('sub{"c:\\\\tmp"}','*.xml','stat $_')

Used METHOD CALL OPTIONS: -', -o-, -e-.

See also lls.

set () -> (slot names of the object)
set (-option) -> value of the option given
set (-option=>value,...) -> self object
set ([command line arguments], -option=>value,...) -> self object

Retrieves and sets values of the SLOTS. $s->{-option} direct access may be used also, but set smartly processes some options.

wmi (?get object) -> wmi

WMI connection or WMI object, after connect, if -init='wmi'.

METHOD CALL OPTIONS

METHOD CALL OPTIONS

Method call options considered as a first argument of method call, beginning with '-' sign and letter. Several options may be catenated into options string without additional '-' signs.

-'
-"

Quoting for string arguments to embed into Perl source. To use on agent side only. Default is '"'.

-b-
-b0

'b'inmode off. Switch off 'binmode' in file operations. Reserved, do not use.

-e-
-e0

refuse STD'e'RR. Remain remote STDERR unredirected.

-e!
-e@
-e#

'e'xecution separator. Command line mark-up sign.

-l
-l+

'l'oop. Start agent script file from agtfile.

-m
-m+
-m1

'm'ove. Move file, delete remote file after transfer to manager.

-o-
-o0

refuse STD'o'UT. Remain remote STDOUT unredirected.

-p
-p+
-p1

'p'ack, alias -z+. Use -pack archiver to compress source for transfer and extract into target directory. fput does not uses archiver if local file is already packed.

-r
-r+
-r1

'r'ecurse (subdirectories).

-s
-s+
-s1

's'tring or 's'calar. Use string value as file content instead of file name.

-z
-z+
-z1

'z'ip, alias -p+.

REMOTE SOURCE EXPANSION

REMOTE SOURCE EXPANSION

Writing Perl as string constants is difficult in escaping. So, many methods accepts lists as arguments, and an array reference (delimited by '[' and ']') may be argument too. This array will be expanded to Perl and embedded within other arguments.

The full syntax is:

        [?command, ?-options, list of arguments]

Where

Command (optional) may be do{, eval{, system, `, see below. Default command is specified within individual METHODS, default options (see METHOD CALL OPTIONS) are inherited from method call.

Default do{ is used within rcmd and fget.

Default system( is used within reval.

do{

Evaluate Perl source within do{}.

eval{

Evaluate Perl source within eval{}.

system(

Execute command line via system call.

`

Execute command line within ``.

REMOTE EVALUATION ENVIRONMENT

REMOTE EVALUATION ENVIRONMENT

There are several variables available for remotely evaluated Perl.

$ENV{SMELEM}

Computer name, for compatibility with Sys::Manage::Cmd command line embedding.

$m_

IO::Socket::INET object, connected to -agent

$r_

Current value evaluated, current return value.

$t_

Temporary file name, alike -tmp.

OLDERR

Saved STDERR file handle.

OLDIN

Saved STDIN file handle.

OLDOUT

Saved STDOUT file handle.

LIMITATIONS, BUGS, PROBLEMS

Limitations, Bugs, Problems

    Implemented and tested with Perl 5.6.0 and 5.8.8 on Windows 2000/2003.

    Output of the remote execution should not contain -mark value.

    Interactive remote execution not supported.

    Requoting of command lines is not exhaustive.

    Binmode for file operations should be off, do not use -b-, it is reserved only.

    Exhaustive timeouts may be implemented only with $SIG{ALRM} and alarm().

    See at the top of the source code.

VERSION

'2009-12-28'

Limitations, Bugs, Problems added.

'2009-03-23'

connect changed: IWbemLocator.ConnectServer(...,wbemConnectFlagUseMaxWait) used when -timeout is undefined or true.

'2008-10-13'

Command line quoting/escaping corrected for 'rsh' -init.

'2008-08-25'

OS error info extended.

'2008-05-13'

Transfer of $@ corrected removing [\r\n] on agent.

'2007-11-08'

fput and fget corrected with attempt to delete unwriteable target file.

'2007-08-31'

Extended mget, mput. Return codes defined and approvement sub{} added to watch replication. Final 'all done' call added to extend Sys::Manage::CmdFile command files.

'2007-08-14'

New isscript.

'2007-08-10'

New -retbps and -retexc, improved time limit condition in mget and mput.

$ENV{SMSECS} considered in mget and mput.

'2007-03-22'

Fixed quoting of arguments in rcmd.

'2007-02-13'

Fixed error indicators ($!, $^E, $@) transfer translating [\n\r\t].

Fixed -wmisis agent file.

Fixed mget/mput recurse.

'2007-02-01'

New -reject.

New -wmisis, changed connect.

'2007-01-30'

New -wmisil, changed connect.

'2007-01-29'

New mput and mget methods.

'2007-01-26'

New rls and lls methods.

'2007-01-24'

connect fixed automatically decreasing WMI ImpersonationLevel from 4 to 3 when security error.

'2005-12-26'

fget correction: manager file is created after agent file opened.

'2005-12-20'

Publishing 0.51 version.

'2005-12-02'

New agtfile method and command. New lcmd command.

'2005-11-25'

Published 0.50 version.

'2005-09-19'

Started

LICENSE

This is free software; you can use redistribute it and/or modify it under the same terms as Perl itself.

AUTHOR

Andrew V Makarow <makarow at mail.com>, for block

2 POD Errors

The following errors were encountered while parsing the POD:

Around line 96:

You can't have =items (as at line 101) unless the first thing after the =over is an =item

Around line 1048:

You forgot a '=back' before '=head1'