Sys::Manage::Conn - Connection to remote Perl
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');
#!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"
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
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.
-v
-echo
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.
-init
-perl
The security is only tcp/ip address of manager, -chkip value with default.
-chkip
This module is implemented and tested with Perl 5.6.0 on Windows 2000.
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 => ''.
agtfile
The usually slots are -init, -node, -user, -echo and -debug, -argv.
-node
-user
-debug
-argv
=> IO::Socket::INET
Connection to remote agent. Established by connect. Used internally.
connect
Evaluated on remote agent code may use $m_ variable.
$m_
=> [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].
set
=> 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.
=> gethostbyname | ''
TCP/IP address of manager (local node or host). Default value is given using gethostbyname (Sys::Hostname or Win32::NodeName).
=> false | true
Debug mode. Automatically sets -echo=3.
=> directory marker sign
Directory marker, '/' or '\', filled automatically using $0 or $^O.
=> working directory
Directory where script started. Obtained using Cwd or Win32::GetCwd.
=> 0 | 1 | 2 | 3
Echo printout level, verbosity level.
0 - none.
1 - print commands invoking alike rcmd or reval.
rcmd
reval
2 - print remote stdout and stderr accepting
3 - print perl sources transfer
See also -debug, -progress.
-progress
=> remote $?
=> remote $?>>8
=> remote $!
=> remote $^E
=> remote $@
Errors from perl source remotely evaluated. Accepted via getret, where also local $? and $@ are filled from -errchild and -erreval.
getret
-errchild
-erreval
See also -reteval.
-reteval
=> 'die' | 'warn' | false
Error or exception processing behaviour.
Execute -argv within -connect. The first argument may be a method name (rcmd, reval, fput, fget,...). Default considered as rcmd.
-connect
fput
fget
=> '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.
=> '----ret$?$!$@: '
Command output end marker. Used by getret to finish -agent reading. Output of the remote execution should not contain -mark value.
-agent
-mark
=> remote node
Remote computer name or TCP/IP address to connect to. See also -port.
-port
=> 'zip' | 'arj' | 'tar'
=> undef | 'unzip' |...
Filesystem packer and unpacker used to provide -p+. There may be a full path to call utility.
-p+
=> 'perl'
Discoverable file name of remote Perl interpreter. Default is 'perl', rely on $ENV{path}.
=> f($0)
Common and full names of script, filled automatically using $0. Common name is used in -tmp value.
-tmp
=> true | false
Output progress with -echo.
=> false | password string
Password to login -user to -node during connect. Default behaviour tries without password
=> 8008
Remote agent TCP/IP port number to listen by IO::Socket::INET. See also -node.
=> 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.
=> 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.
mget
mput
=> false || true
Mark of excess achieved, i.e. time limit in mget or mput.
=> value or data structure
Result of evaluation of remote Perl source accepted by getret. Result of last reval.
=> 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.
-dirm
-prgcn
Evaluated on remote agent code may use $t_ variable.
$t_
=> undef
Network operations timeout.
=> 'Remote command stream'
Title to display sometimes...
=> false | user name
Remote user name to login to -node inside connect. -pswd also may be required. Default is current user.
-pswd
=> undef | WMI object
Windows WMI Win32::OLE connection, if opened by connect.
=> 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.
=> 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.
The main methods are new, connect, reval, rcmd, fput, fget, rdo.
new
rdo
Writes separate agent script file to be used with -init => ''.
Used METHOD CALL OPTIONS: -', -l.
METHOD CALL OPTIONS
-'
-l
Connects to remote -node, using -init, -user, -pswd. Starts remote -perl with command line IO::Socket::INET agent on -port, connects -agent to it.
Closes connection opened.
Proceeds error according to -error. Returns undef, if returns.
-error
Reads remote file and writes it locally.
Used METHOD CALL OPTIONS: -', -m, -b-, -s+, -p+.
-m
-b-
-s+
Default REMOTE SOURCE EXPANSION: do{.
REMOTE SOURCE EXPANSION
do{
See also rfread.
rfread
Reads local file and writes it remotely.
With -p+ option, archiver will not be used if local file is already packed.
See also rfwrite.
rfwrite
Checks if $0 is from library specified, alike Sys::Manage::Cmd::isscript, uses $ENV{SMDIR} and $ENV{SMLIB}. Useful for -reject.
-reject
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.
Reads local file and returns it's content.
Used METHOD CALL OPTIONS: -b-.
See also rfread, lfwrite.
lfwrite
Writes to local file content given.
See also rfwrite, lfread.
lfread
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.
rls
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.
-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');
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.
See also fput, mget.
$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');
Creates new Sys::Manage::Conn object. See also set syntax.
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-.
-o-
-e-
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".
-e!
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'
Remotely evaluates Perl source given. Returns result transferred using Data::Dumper.
Used METHOD CALL OPTIONS: -o-, -e-.
Default REMOTE SOURCE EXPANSION: system(.
system(
Reads remote file and returns it's content.
Used METHOD CALL OPTIONS: -', -b-.
See also lfread, rfget, rfwrite.
rfget
Writes to remote file content given.
See also lfwrite, rfput, rfread.
rfput
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 $_')
See also lls.
lls
Retrieves and sets values of the SLOTS. $s->{-option} direct access may be used also, but set smartly processes some options.
SLOTS
WMI connection or WMI object, after connect, if -init='wmi'.
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'inmode off. Switch off 'binmode' in file operations. Reserved, do not use.
refuse STD'e'RR. Remain remote STDERR unredirected.
'e'xecution separator. Command line mark-up sign.
'l'oop. Start agent script file from agtfile.
'm'ove. Move file, delete remote file after transfer to manager.
refuse STD'o'UT. Remain remote STDOUT unredirected.
'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.
-z+
-pack
'r'ecurse (subdirectories).
's'tring or 's'calar. Use string value as file content instead of file name.
'z'ip, alias -p+.
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.
eval{
system
`
METHODS
Default do{ is used within rcmd and fget.
Default system( is used within reval.
Evaluate Perl source within do{}.
Evaluate Perl source within eval{}.
Execute command line via system call.
Execute command line within ``.
There are several variables available for remotely evaluated Perl.
Computer name, for compatibility with Sys::Manage::Cmd command line embedding.
IO::Socket::INET object, connected to -agent
Current value evaluated, current return value.
Temporary file name, alike -tmp.
Saved STDERR file handle.
Saved STDIN file handle.
Saved STDOUT file handle.
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.
Limitations, Bugs, Problems added.
Limitations, Bugs, Problems
connect changed: IWbemLocator.ConnectServer(...,wbemConnectFlagUseMaxWait) used when -timeout is undefined or true.
-timeout
Command line quoting/escaping corrected for 'rsh' -init.
OS error info extended.
Transfer of $@ corrected removing [\r\n] on agent.
fput and fget corrected with attempt to delete unwriteable target file.
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.
New isscript.
isscript
New -retbps and -retexc, improved time limit condition in mget and mput.
-retbps
-retexc
$ENV{SMSECS} considered in mget and mput.
Fixed quoting of arguments in rcmd.
Fixed error indicators ($!, $^E, $@) transfer translating [\n\r\t].
Fixed -wmisis agent file.
-wmisis
Fixed mget/mput recurse.
New -reject.
New -wmisis, changed connect.
New -wmisil, changed connect.
-wmisil
New mput and mget methods.
New rls and lls methods.
connect fixed automatically decreasing WMI ImpersonationLevel from 4 to 3 when security error.
fget correction: manager file is created after agent file opened.
Publishing 0.51 version.
New agtfile method and command. New lcmd command.
lcmd
Published 0.50 version.
Started
This is free software; you can use redistribute it and/or modify it under the same terms as Perl itself.
Andrew V Makarow <makarow at mail.com>, for block
2 POD Errors
The following errors were encountered while parsing the POD:
You can't have =items (as at line 101) unless the first thing after the =over is an =item
You forgot a '=back' before '=head1'
To install Sys::Manage::Cmd, copy and paste the appropriate command in to your terminal.
cpanm
cpanm Sys::Manage::Cmd
CPAN shell
perl -MCPAN -e shell install Sys::Manage::Cmd
For more information on module installation, please visit the detailed CPAN module installation guide.