Sysadm::Install(3pm) | User Contributed Perl Documentation | Sysadm::Install(3pm) |
Sysadm::Install - Typical installation tasks for system administrators
use Sysadm::Install qw(:all); my $INST_DIR = '/home/me/install/'; cd($INST_DIR); cp("/deliver/someproj.tgz", "."); untar("someproj.tgz"); cd("someproj"); # Write out ... blurt("Builder: Mike\nDate: Today\n", "build.dat"); # Slurp back in ... my $data = slurp("build.dat"); # or edit in place ... pie(sub { s/Today/scalar localtime()/ge; $_; }, "build.dat"); make("test install"); # run a cmd and tap into stdout and stderr my($stdout, $stderr, $exit_code) = tap("ls", "-R");
Have you ever wished for your installation shell scripts to run reproducibly, without much programming fuzz, and even with optional logging enabled? Then give up shell programming, use Perl.
"Sysadm::Install" executes shell-like commands performing typical installation tasks: Copying files, extracting tarballs, calling "make". It has a "fail once and die" policy, meticulously checking the result of every operation and calling "die()" immediately if anything fails.
"Sysadm::Install" also supports a dry_run mode, in which it logs everything, but suppresses any write actions. Dry run mode is enabled by calling Sysadm::Install::dry_run(1). To switch back to normal, call Sysadm::Install::dry_run(0).
As of version 0.17, "Sysadm::Install" supports a confirm mode, in which it interactively asks the user before running any of its functions (just like "rm -i"). confirm mode is enabled by calling Sysadm::Install::confirm(1). To switch back to normal, call Sysadm::Install::confirm(0).
"Sysadm::Install" is fully Log4perl-enabled. To start logging, just initialize "Log::Log4perl". "Sysadm::Install" acts as a wrapper class, meaning that file names and line numbers are reported from the calling program's point of view.
pick("Pick a fruit", ["apple", "pear", "pineapple"], 3);
will display the following:
[1] apple [2] pear [3] pineapple Pick a fruit [3]>
If the user just hits Enter, "pineapple" (the default value) will be returned. Note that 3 marks the 3rd element of the list, and is not an index value into the array.
If the user enters 1, 2 or 3, the corresponding text string ("apple", "pear", "pineapple" will be returned by "pick()".
If the optional $opts hash has "{ tty => 1 }" set, then the user response will be expected from the console, not STDIN.
If the optional $opts hash has "{ tty => 1 }" set, then the user response will be expected from the console, not STDIN.
cd($dir, {stack_update => 0});
# go all the way back cdback( { reset => 1 } );
Example:
# Replace all 'foo's by 'bar' in test.dat pie(sub { s/foo/bar/g; $_; }, "test.dat");
Works with one or more file names.
If the files are known to contain UTF-8 encoded data, and you want it to be read/written as a Unicode strings, use the "utf8" option:
pie(sub { s/foo/bar/g; $_; }, "test.dat", { utf8 => 1 });
Example:
# Print all lines containing 'foobar' plough(sub { print if /foobar/ }, "test.dat");
Works with one or more file names.
If the files are known to contain UTF-8 encoded data, and you want it to be read into Unicode strings, use the "utf8" option:
plough(sub { print if /foobar/ }, "test.dat", { utf8 => 1 });
If the file is known to contain UTF-8 encoded data and you want to read it in as a Unicode string, use the "utf8" option:
my $unicode_string = slurp( $file, {utf8 => 1} );
If the string is a Unicode string, use the "utf8" option:
blurt( $unicode_string, $file, {utf8 => 1} );
Unlike in "blurt", there is no $append mode in "blurt_atomic".
If the string is a Unicode string, use the "utf8" option:
blurt_atomic( $unicode_string, $file, {utf8 => 1} );
Please note that "tap()" is limited to single shell commands, it won't work with output redirectors ("ls >/tmp/foo" 2>&1).
In default mode, "tap()" will concatenate the command and args given and create a shell command line by redirecting STDERR to a temporary file. "tap("ls", "/tmp")", for example, will result in
'ls' '/tmp' 2>/tmp/sometempfile |
Note that all commands are protected by single quotes to make sure arguments containing spaces are processed as singles, and no globbing happens on wildcards. Arguments containing single quotes or backslashes are escaped properly.
If quoting is undesirable, "tap()" accepts an option hash as its first parameter,
tap({no_quotes => 1}, "ls", "/tmp/*");
which will suppress any quoting:
ls /tmp/* 2>/tmp/sometempfile |
Or, if you prefer double quotes, use
tap({double_quotes => 1}, "ls", "/tmp/$VAR");
wrapping all args so that shell variables are interpolated properly:
"ls" "/tmp/$VAR" 2>/tmp/sometempfile |
Another option is "utf8" which runs the command in a terminal set to UTF8.
Error handling: By default, tap() won't raise an error if the command's return code is nonzero, indicating an error reported by the shell. If bailing out on errors is requested to avoid return code checking by the script, use the raise_error option:
tap({raise_error => 1}, "ls", "doesn't exist");
In DEBUG mode, "tap" logs the entire stdout/stderr output, which can get too verbose at times. To limit the number of bytes logged, use the "stdout_limit" and "stderr_limit" options
tap({stdout_limit => 10}, "echo", "123456789101112");
print "foo!\n";
and want to put it into a double-quoted string, it will look like
"print \"foo!\\n\""
Sometimes, not only backslashes and double quotes need to be escaped, but also the target environment's meta chars. A string containing
print "$<\n";
needs to have the '$' escaped like
"print \"\$<\\n\";"
if you want to reuse it later in a shell context:
$ perl -le "print \"\$<\\n\";" 1212
"qquote()" supports escaping these extra characters with its second, optional argument, consisting of a string listing all escapable characters:
my $script = 'print "$< rocks!\\n";'; my $escaped = qquote($script, '!$'); # Escape for shell use system("perl -e $escaped"); => 1212 rocks!
And there's a shortcut for shells: By specifying ':shell' as the metacharacters string, qquote() will actually use '!$`'.
For example, if you wanted to run the perl code
print "foobar\n";
via
perl -e ...
on a box via ssh, you would use
use Sysadm::Install qw(qquote); my $cmd = 'print "foobar!\n"'; $cmd = "perl -e " . qquote($cmd, ':shell'); $cmd = "ssh somehost " . qquote($cmd, ':shell'); print "$cmd\n"; system($cmd);
and get
ssh somehost "perl -e \"print \\\"foobar\\\!\\\\n\\\"\""
which runs on "somehost" without hickup and prints "foobar!".
Sysadm::Install comes with a script "one-liner" (installed in bin), which takes arbitrary perl code on STDIN and transforms it into a one-liner:
$ one-liner Type perl code, terminate by CTRL-D print "hello\n"; print "world\n"; ^D perl -e "print \"hello\\n\"; print \"world\\n\"; "
Note that shells typically don't support escaped single quotes within single quotes, which means that
$ echo 'foo\'bar' >
is invalid and the shell waits until it finds a closing quote. Instead, there is an evil trick which gives the desired result:
$ echo 'foo'\''bar' # foo, single quote, \, 2 x single quote, bar foo'bar
It uses the fact that shells interpret back-to-back strings as one. The construct above consists of three back-to-back strings:
(1) 'foo' (2) ' (3) 'bar'
which all get concatenated to a single
foo'bar
If you call "quote()" with $metachars set to ":shell", it will perform that magic behind the scenes:
print quote("foo'bar"); # prints: 'foo'\''bar'
For example: copy uid/gid of the containing directory to a file therein:
use File::Basename; owner_cp( dirname($file), $file );
Usually requires root privileges, just like chown does.
sudo scriptname args ...
Make sure to call this before any @ARGV-modifying functions like "getopts()" have kicked in.
cd $dir; find ./ -xdev -print0 | cpio -o0 |
This can be used to capture a file system structure.
| (cd $dir; cpio -i0)
process to restore a file system structure. To be used in conjunction with fs_read_open.
If $data is longer than $maxlen, it will be formatted like
(22)[abcdef[snip=11]stuvw]
indicating the length of the original string, the beginning, the end, and the number of 'snipped' characters.
If $data is shorter than $maxlen, it will be returned unmodified (except for unprintable characters replaced, see below).
If $data contains unprintable character's they are replaced by "." (the dot).
password: ***** (stars aren't actually displayed)
This function will switch the terminal back into normal mode after the user hits the 'Return' key.
If the optional $opts hash has "{ tty => 1 }" set, then the prompt will be redirected to the console instead of STDOUT.
print nice_time(), "\n"; # 2007/04/01 10:51:24
It uses the system time by default, but it can also accept epoch seconds:
print nice_time(1170000000), "\n"; # 2007/01/28 08:00:00
It uses localtime() under the hood, so the outcome of the above will depend on your local time zone setting.
if(!defined $foo) { $foo = $default; }
you can just write
$foo //= $default;
However, this is not available on older perl versions (although there's source filter solutions). Often, people use
$foo ||= $default;
instead which is wrong if $foo contains a value that evaluates as false. So Sysadm::Install, the everything-and-the-kitchen-sink under the CPAN modules, provides the function "def_or()" which can be used like
def_or($foo, $default);
to accomplish the same as
$foo //= $default;
How does it work, how does $foo get a different value, although it's apparently passed in by value? Modifying $_[0] within the subroutine is an old Perl trick to do exactly that.
Mike Schilli, <m@perlmeister.com>
Copyright (C) 2004-2007 by Mike Schilli
This library is free software; you can redistribute it and/or modify it under the same terms as Perl itself, either Perl version 5.8.3 or, at your option, any later version of Perl 5 you may have available.
2022-06-17 | perl v5.34.0 |