File: postinst.pl

package info (click to toggle)
ocsinventory-agent 2:2.4.2-3
  • links: PTS, VCS
  • area: main
  • in suites: buster, sid
  • size: 6,224 kB
  • sloc: perl: 27,179; xml: 773; objc: 490; ansic: 333; sh: 316; makefile: 12
file content (578 lines) | stat: -rwxr-xr-x 18,515 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
#!/usr/bin/perl -w

use strict;

use lib 'lib';

use Cwd;
use Ocsinventory::Agent::Config;


my $old_unix_agent_dir = "/etc/ocsinventory-client";

my $config;
my @cacert;
my $binpath;
my $randomtime;
my $crontab;
my $cron_line;
my $option;
my $nowizard;
my $configdir;
my $remove_old_unix;
my $old_unix_config;
my $nossl;
my $download;
my $snmp;
my $now;


for $option (@ARGV){
    if ($option=~/--nowizard$/){
        $nowizard = 1;
    } elsif($option=~/--server=(\S*)$/){
        $config->{server} = $1;
    } elsif($option=~/--basevardir=(\S*)$/){
        $config->{basevardir} = $1;
    } elsif($option=~/--configdir=(\S*)$/){
        $configdir = $1;
    } elsif($option=~/--user=(\S*)$/){
        $config->{user} = $1;
    } elsif($option=~/--password=(\S*)$/){
        $config->{password} = $1;
    } elsif($option=~/--realm=(\S*)$/){
        $config->{realm} = $1;
    } elsif($option=~/--tag=(\S*)$/){
        $config->{tag} = $1;
    } elsif($option=~/--crontab$/){
        $crontab = 1;
    } elsif($option=~/--get-old-unix-agent-config$/){
        $old_unix_config = 1;
    } elsif($option=~/--remove-old-unix-agent$/){
        $remove_old_unix = 1;
    } elsif($option=~/--debug$/){
        $config->{debug} = 1;
    } elsif($option=~/--logfile=(\S*)$/){
        $config->{logfile} = $1;
    } elsif($option=~/--nossl$/){
        $nossl = 1;
    } elsif($option=~/--ca=(\S*)$/){
        $config->{ca} = $1;
    } elsif($option=~/--download$/){
        $download = 1;
    } elsif($option=~/--snmp$/){
        $snmp = 1;
    } elsif($option=~/--now$/){
        $now = 1;
    } elsif($option=~/--help/ || $option=~/-h/) {
        print STDERR <<EOF;
Usage :
\t--nowizard                    launch this script without interaction
\t--server=url                  set OCS Inventory NG server address (e.g: http://ocsinventory-ng/ocsinventory) 
\t--basevardir=path             set OCS Inventory NG Unix Unified agent variables directory (e.g: /var/lib/ocsinventory-agent)
\t--configdir=path              set OCS Inventory NG Unix Unified configuration directory (e.g: /etc/ocsinventory-agent)
\t--user=username               set username for OCS Inventory server Apache authentication (if needed)
\t--password=password           set password for OCS Inventory NG server Apache authentication (if needed)
\t--realm=realm                 set realm name for OCS Inventory NG server Apache authentication (if needed)
\t--crontab                     set a crontab while installing OCS Inventory NG Unix Unified agent
\t--get-old-unix-agent-config   retrieve old OCS Inventory NG Unix agent configuration (if needed)
\t--remove-old-unix-agent       remove old OCS Inventory NG Unix agent from system (if needed)
\t--debug                       activate debug mode configuration option while installing OCS Inventory NG Unix Unified agent
\t--logfile=path                set OCS Inventory NG Unix Unified agent log file path (if needed) 
\t--nossl                       disable SSL CA verification configuration option while installing OCS Inventory NG Unix Unified agent (not recommended)
\t--ca=path                     set OCS Inventory NG Unix Unified agent CA certificate chain file path
\t--download                    activate package deployment feature while installing OCS Inventory NG Unix Unified agent
\t--snmp                        activate SNMP scans feature while installing OCS Inventory NG Unix Unified agent
\t--now                         launch OCS Inventory NG Unix Unified agent after installation
\t-h --help                     display this help
EOF

        exit 0;
    }
}


loadModules (qw/XML::Simple ExtUtils::MakeMaker/);

############ Setting default values ############

my @default_configdirs = ("/etc/ocsinventory", "/usr/local/etc/ocsinventory", "/etc/ocsinventory-agent");

unless ($config->{basevardir}) {
    if ($^O =~ /solaris/) {
        $config->{basevardir} = '/var/opt/ocsinventory-agent';
    } elsif ($^O =~ /bsd/) {
        $config->{basevardir} = '/var/db/ocsinventory-agent';
    } else { 
        $config->{basevardir} = '/var/lib/ocsinventory-agent'
    }
}


############ Asking for questions ##############
unless ($nowizard) {
    if (!ask_yn("Do you want to configure the agent", 'y')) {
         exit 0;
    }
  
    unless ($configdir) {
        $configdir = getConfigDir (@default_configdirs);

        #If not found
        unless (-d $configdir) {
            $configdir = askConfigDir (@default_configdirs);
            unless (-d $configdir) {
                unless (ask_yn ("Do you want to create the directory ".$configdir."?", 'y')) {
                    die("Please create  ".$configdir." directory first.\n");
                }
            }
        }
    }

    #Old unix agent
    if (ask_yn("Should the old unix_agent settings be imported ?", 'y')) {
        $old_unix_config=1;
    }

    #Getting agent configuration if exists
    if (-f $configdir."/ocsinventory-agent.cfg") {
        open (CONFIG, "<".$configdir."/ocsinventory-agent.cfg") or
        die "Can't open ".$configdir."/ocsinventory-agent.cfg: ".$!;

        foreach (<CONFIG>) {
            s/#.+//;
            if (/(\w+)\s*=\s*(.+)/) {
                 my $key = $1;
                 my $val = $2;
                 # Remove the quotes
                 $val =~ s/\s+$//;
                 $val =~ s/^'(.*)'$/$1/;
                 $val =~ s/^"(.*)"$/$1/;
                 $config->{$key} = $val unless $config->{$key};
            }
        }
        close CONFIG;
    }

    #Getting server name 
    print "[info] The config file will be written in $configdir/ocsinventory-agent.cfg,\n";
    $config->{server} = promptUser('What is the address of your ocs server',$config->{server});
    #$config->{server} = promptUser('What is the address of your ocs server', exists ($config->{server})?$config->{server}:'ocsinventory-ng');

    #Getting credentials if needed
    if (ask_yn ("Do you need credential for the server? (You probably don't)", 'n')) {
        $config->{user} = promptUser("user", $config->{user});
        $config->{password} = promptUser("password");
        print "[info] The realm can be found in the login popup of your Internet browser.\n[info] In general, it's something like 'Restricted Area'.\n";
        $config->{realm} = promptUser("realm");
    }

    #Getting tag
    unless ($config->{tag}){
        if (ask_yn('Do you want to apply an administrative tag on this machine', 'y')) {
            $config->{tag} = promptUser("tag", $config->{tag});
        }
    }

    #Getting crontab
    if ($^O =~ /solaris/ || $^O =~ /bsd/) {
        if (ask_yn("Do yo want to install the cron task in current user crontab ?", 'y')) {
            $crontab = 1;
        }
    } elsif (-d "/etc/cron.d") {
        if (ask_yn("Do yo want to install the cron task in /etc/cron.d", 'y')) {
            $crontab = 1;
        }
    }

    #Getting basevardir
    $config->{basevardir} = promptUser('Where do you want the agent to store its files? (You probably don\'t need to change it)', $config->{basevardir}, '^\/\w+', 'The location must begin with /');

    unless (-d $config->{basevardir}) {
        unless (ask_yn ("Do you want to create the ".$config->{basevardir}." directory?\n", 'y')) {
            die("Please create the ".$config->{basevardir}." directory manually and relaunch postinst.pl script\n");
        }
    }

    #Remove old unix agent ?
    $remove_old_unix = ask_yn ("Should I remove the old unix_agent", 'n') unless $remove_old_unix;

    #Enable debug option ?
    $config->{debug} = ask_yn("Do you want to activate debug configuration option ?", 'y') unless $config->{debug};

    #Enable log file ?
    unless ($config->{logfile}) {
        if (ask_yn("Do you want to use OCS Inventory NG UNix Unified agent log file ?", 'y')){ 
            $config->{logfile} = promptUser('Specify log file path you want to use', $config->{logfile}, '^\/\w+', 'The location must begin with /');
        }
    }

    #Disable SSL option ?
    unless ($nossl) {
        $nossl = ask_yn("Do you want disable SSL CA verification configuration option (not recommended) ?", 'n');
    }

    #Set CA certificate path ?
    unless ($config->{ca}) {
        if (ask_yn("Do you want to set CA certificate chain file path ?", 'y')){ 
            $config->{ca} = promptUser('Specify CA certificate chain file path', $config->{ca}, '^\/\w+', 'The location must begin with /');
        }
    }

    #Enable download feature ?
    $download = ask_yn("Do you want to use OCS-Inventory software deployment feature?", 'y') unless $download;

    #Enable SNMP feature ?
    $snmp = ask_yn("Do you want to use OCS-Inventory SNMP scans feature?", 'y') unless $snmp;

    #Run agent after configuration ?
    $now = ask_yn("Do you want to send an inventory of this machine?", 'y') unless $now;

}


################ Here we go... ##############

#Old unix agent
if (-f $old_unix_agent_dir.'/ocsinv.conf' && $old_unix_config) {
  
    print STDERR "Getting old OCS Inventory NG Unix agent configuration...\n";
    my $ocsinv = XMLin($old_unix_agent_dir.'/ocsinv.conf');
    $config->{server} = mkFullServerUrl($ocsinv->{'OCSFSERVER'});

    if (-f $old_unix_agent_dir.'/cacert.pem') {
        open CACERT, $old_unix_agent_dir.'/cacert.pem' or die "Can't import the CA certificate: ".$!;
        @cacert = <CACERT>;
        close CACERT;
    }

    my $admcontent = '';

    if (-f "$old_unix_agent_dir/ocsinv.adm") {
        if (!open(ADM, "<:encoding(iso-8859-1)", "$old_unix_agent_dir/ocsinv.adm")) {
            warn "Can't open $old_unix_agent_dir/ocsinv.adm";
        } else {
            $admcontent .= $_ foreach (<ADM>);
            close ADM;
            my $admdata = XMLin($admcontent) or die;
            if (ref ($admdata->{ACCOUNTINFO}) eq 'ARRAY') {
                foreach (@{$admdata->{ACCOUNTINFO}}) {
                    $config->{tag} = $_->{KEYVALUE} if $_->{KEYNAME} =~ /^TAG$/;
                }
            } elsif (
                exists($admdata->{ACCOUNTINFO}->{KEYNAME}) &&
                exists($admdata->{ACCOUNTINFO}->{KEYVALUE}) &&
                $admdata->{ACCOUNTINFO}->{KEYNAME} eq 'TAG'
                ){
                    print $admdata->{ACCOUNTINFO}->{KEYVALUE}."\n";
                    $config->{tag} = $admdata->{ACCOUNTINFO}->{KEYVALUE};
            }
        }
    }
}


#Setting server uri
print STDERR "Setting OCS Inventory NG server address...\n";

$config->{server}="ocsinventory-ng" unless $config->{server};
$config->{server} = mkFullServerUrl($config->{server});

if (!$config->{server}) {
    print "Server is empty. Leaving...\n";
    exit 1;
}
my $uri;
if ($config->{server} =~ /^http(|s):\/\//) {
    $uri = $config->{server};
} else { # just the hostname
    $uri = "http://".$config->{server}."/ocsinventory"
}


#Is OCS agent well installed ?
print STDERR "Looking for OCS Invetory NG Unix Unified agent installation...\n";
chomp($binpath = `which ocsinventory-agent 2>/dev/null`);
if (! -x $binpath) {
    # Packaged version with perl and agent ?
    $binpath = $^X;
    $binpath =~ s/perl/ocsinventory-agent/;
}

if (! -x $binpath) {
    print "sorry, can't find ocsinventory-agent in \$PATH\n";
    exit 1;
} else {
    print "ocsinventory agent presents: $binpath\n";
}


#Setting crontab
$randomtime = int(rand(60)).' '.int(rand(24));
$cron_line = $randomtime." * * * root $binpath --lazy > /dev/null 2>&1\n";

if ($crontab) {

    print STDERR "Setting crontab...\n";

    if ($^O =~ /solaris/ || $^O =~ /bsd/) {
        my $cron = `crontab -l`;

        # Let's suppress Unix cron/anacron user column
        $cron_line =~ s/ root /  /;
        $cron .= $cron_line;

        open CRONP, "| crontab" || die "Can't run crontab: $!";
        print CRONP $crontab;
        close(CRONP);
    } elsif (-d "/etc/cron.d") {
        open DEST, '>/etc/cron.d/ocsinventory-agent' or die $!;
        # Save the root PATH
        print DEST "PATH=".$ENV{PATH}."\n";
        print DEST $randomtime." * * * root $binpath --lazy > /dev/null 2>&1\n";
        close DEST;
    }
}

#Creating basevardir
if (!-d $config->{basevardir}) {
    print STDERR "Creating $config->{basevardir} directory...\n";
    mkdir $config->{basevardir} or die $!;
}

#Disabling SSL verification if asked
$config->{ssl} = 0 if $nossl;

#Creating configuration directory 
$configdir = "/etc/ocsinventory-agent" unless $configdir;  #If not set in command line

if (grep (/$configdir/,@default_configdirs)) {
    $configdir = '/etc/ocsinventory-agent' unless $configdir;

    print STDERR "Creating $configdir directory...\n";

    unless (-d $configdir) {
        unless (mkdir $configdir) {
            die("Failed to create ".$configdir.". Are you root?\n");
        }
    }
    print STDERR "Writing OCS Inventory NG Unix Unified agent configuration\n";
    open CONFIG, ">$configdir/ocsinventory-agent.cfg" or die "Can't write the config file in $configdir: ".$!;
    print CONFIG $_."=".$config->{$_}."\n" foreach (keys %$config);
    close CONFIG;
    chmod 0600, "$configdir/ocsinventory-agent.cfg";
} else {
    die("Wrong configuration directory...please choose a directory supported by OCS Inventory NG agent !!!\n");
}


#Removing old unix agent if needed
if ($remove_old_unix) {
    print STDERR "Removing old OCS Inventory Unix agent...\n";
    foreach (qw#
        /etc/ocsinventory-client
        /etc/logrotate.d/ocsinventory-client
        /usr/sbin/ocsinventory-client.pl
        /etc/cron.d/ocsinventory-client
        /bin/ocsinv
        #) {
        print $_."\n";
        next;
        rmdir if -d;
        unlink if -f || -l;
    }
    print "done\n"
}

# Creating vardirectory for this server
my $dir = $config->{server};
$dir =~ s/\//_/g;
my $vardir = $config->{basevardir}."/".$dir;
print STDERR "Creating $vardir directory...\n";
recMkdir($vardir) or die "Can't create $vardir!";

if (@cacert) { # we need to migrate the certificate
    print STDERR "Copying cacert.pem in $vardir...\n";

    open CACERT, ">".$vardir."/cacert.pem" or die "Can't open ".$vardir.'/cacert.pem: '.$!;
    print CACERT foreach (@cacert);
    close CACERT;
    print "Certificate copied in ".$vardir."/cacert.pem\n";
}

#We copy custom XML for SNMP MIBs from sources
my $workdir = getcwd();
my $source_snmpdir = "$workdir/snmp";
my $snmpdir = "$vardir/snmp";

if ( -d $source_snmpdir && -d $vardir) {
    unless (-d $snmpdir) {
        print STDERR "Creating $snmpdir directory...\n";
        recMkdir($snmpdir) or die "Can't create $snmpdir!";
    }
    print STDERR "Copying SNMP MIBs XML files...\n";
    system("cp -r $source_snmpdir/* $snmpdir");
}

print STDERR "Activating modules if needed...\n";

open MODULE, ">$configdir/modules.conf" or die "Can't write modules.conf in $configdir: ".$!;
print MODULE "# this list of module will be load by the at run time\n";
print MODULE "# to check its syntax do:\n";
print MODULE "# #perl modules.conf\n";
print MODULE "# You must have NO error. Else the content will be ignored\n";
print MODULE "# This mechanism goal is to launch agent extension modules\n";
print MODULE "\n";
print MODULE ($download?'':'#');
print MODULE "use Ocsinventory::Agent::Modules::Download;\n";
print MODULE ($snmp?'':'#');
print MODULE "use Ocsinventory::Agent::Modules::Snmp;\n";
print MODULE "\n";
print MODULE "# DO NOT REMOVE THE 1;\n";
print MODULE "1;\n";
close MODULE;


#Prevent security risks by removing existing snmp_com.txt file which is no longer used
my $snmp_com_file = "$snmpdir/snmp_com.txt";
if ( -f $snmp_com_file ) {
    print STDERR "$snmp_com_file seems to exists...removing it to prevent security risks !\n";
    unlink $snmp_com_file;
}

# Launch agent if asked
if ($now) {
    print STDERR "Launching OCS Inventory NG Unix Unified agent...\n";

    system("$binpath --force");
    if (($? >> 8)==0) {
        print "   -> Success!\n";
    } else {
        print "   -> Failed!\n";
        print "You may want to launch the agent with the --verbose or --debug flag.\n";
    }
}

#End
print "New settings written! Thank you for using OCS Inventory\n";

######## Subroutines ################

sub loadModules {
    my @modules = @_;

    foreach (@modules) {
        eval "use $_;";
        if ($@) {
            print STDERR "Failed to load $_. Please install it and restart the postinst.pl script ( ./postinst.pl ).\n";
            exit 1;
        }
    }
}

sub ask_yn {
    my $promptUser = shift;
    my $default = shift;

    die unless $default =~ /^(y|n)$/;

    my $cpt = 5;
    while (1) {
        my $line = prompt("$promptUser\nPlease enter 'y' or 'n'?>", $default);
        return 1 if $line =~ /^y$/;
        return if $line =~ /^n$/;
        if ($cpt-- < 0) {
            print STDERR "to much user input, exit...\n";
            exit(0);
        }
    }
}

sub promptUser {
    my ($promptUser, $default, $regex, $notice) = @_;

    my $string = $promptUser;
    $string .= "?>";

    my $line;
    my $cpt = 5;

    while (1) {
        $line = prompt($string, $default);
        if ($regex && $line !~ /$regex/) {
            print STDERR $notice."\n";
        } else {
            last;
        }
        if ($cpt-- < 0) {
            print STDERR "to much user input, exit...\n";
            exit(0);
        }
    }
    return $line;
}

sub getConfigDir {
    my @choices = @_;

    foreach (@choices) {
        my $t = $_.'/ocsinventory-agent.cfg';
        if (-f $t) {
            print "Config file found are $t! Reusing it.\n";
            return $_; 
        }
    }
}

sub askConfigDir {
    my @choices = @_;

    print STDERR "Where do you want to write the configuration file?\n";
    foreach (0..$#choices) {
        print STDERR " ".$_." -> ".$choices[$_]."\n";
    }
    my $input = -1;
    my $configdir;
    while (1) {
        $input = prompt("?>");
        if ($input =~ /^\d+$/ && $input >= 0 && $input <= $#choices) {
            last;
        } else {
            print STDERR "Value must be between 0 and ".$#choices."\n";
        }
    }

    return $choices[$input];
}

sub recMkdir {
    my $dir = shift;

    my @t = split /\//, $dir;
    shift @t;
    return unless @t;

    my $t;
    foreach (@t) {
        $t .= '/'.$_;
        if ((!-d $t) && (!mkdir $t)) {
            return;
        }
    }
    1;
}

sub mkFullServerUrl {

    my $server = shift;

    my $ret = 'http://' unless $server =~ /^http(s|):\/\//;
    $ret .= $server;
   
    if ($server !~ /http(|s):\/\/\S+\/\S+/) {
        $ret .= '/ocsinventory';
    }

    return $ret;

}