Allen Cs Assignment 2

download Allen Cs Assignment 2

of 13

description

CSH and BASH

Transcript of Allen Cs Assignment 2

BASH1: Write a script called simple-useradd.sh that adds a local user to the system. This script should:i) Take only one argument, or else exit after printing a usage message.

ii) Check /etc/passwd and decide on the first free user ID. Print a messagecontaining this ID.

iii) Create a private group for this user, checking the /etc/group file. Print amessage containing the group ID.

iv) Gather information from the operator user: a comment describing this user,choice from a list of shells (CSH and BASH will do, test for acceptability, elseexit printing a message), expiration date for this account, extra groups ofwhich the new user should be a member.

v) With the obtained information, add a line to /etc/passwd, /etc/group and/etc/shadow; create the user's home directory (with correct permissions!); addthe user to the desired secondary groups.

vi) Set the password for this user to a default known string.Answer : #!/bin/bash# Script to add a user to Linux systemHOME_BASE=/home/SHELL=/bin/bash

read -p Username: USERread -s -p Password: PASSWORDegrep -w ^$USER /etc/passwd >/dev/nullif [ $# -ne 1 ]echo "Command arguement cannot be more than one or less!"exit 1else if [ $? -eq 0 ]; thenecho "$username exists!"exit 1elsePASS=$(perl -e print crypt($ARGV[0], password) $PASSWORD) useradd -p ${PASS} -s $SHELL -m -d ${HOME_BASE}${USER} ${USER} [ $? -eq 0 ] && echo -e \nUser has been added to system!\n || echo -e \nFailed to add a user!\nfi

2: Write a script called homebackup that automates tar so the personexecuting the script always uses the desired options (cvp) and backupdestination directory (/var/backups) to make a backup of his or her home directory. Implement the following features:

i) Test for the number of arguments. The script should run without arguments.If any arguments are present, exit after printing a usage message.

ii) Determine whether the backups directory has enough free space to holdthe backup.

iii) Ask the user whether a full or an incremental backup is wanted. If the userdoes not have a full backup file yet, print a message that a full backup will betaken. In case of an incremental backup, only do this if the full backup is notolder than a week.

iv) Compress the backup using any compression tool. Inform the user that thescript is doing this, because it might take some time, during which the usermight start worrying if no output appears on the screen.

v) Print a message informing the user about the size of the compressedbackup.

#!/bin/shif [ $# -ne 0 ]echo "No Command arguement can be present at this moment!"exit 1fi

# What to backup. datapath='/home'

# Where to backup to.backuppath="/var/backup"

# checking the size and space.backupsize=$df -h "/home/"availspace=$df -h "/dev/hda1"

if [ $availspace < $backupsize ]echo "Not enough free space to hold the backup"exit 1fi

# checking the file exsit.ckfile=$ls -l "$dest"

# Backup type

if [ $ckfile < 1 ]; then echo "No previoud backup found, System is doing Full Backup from $backup_files to $dest/$archive_file" echo "Tar compression tool will be used, it might take some times."else

echo "Select a backup type"echo "Key in 1 for Full backup or 2 for Incremental backup" read bktype if [ $bktype -eq 1 ]; thenecho "System is now doing a Full Backup from $backup_files to $dest/$archive_file"echo "Tar compression tool will be used, it might take some times."

# check last modified dateif [ "$(date +%a)" = "Mon" && $bktype -eq 2 ]; thenckdate=$(stat -c %y $hostname-$day.tgz)"ckdate=($ckdate - $day)# Print start status message.echo "System is now doing a Incremental Backup from $backup_files to $dest/$archive_file"echo "Tar compression tool will be used, it might take some times."# move the old backup file to last week fullbackup='-full' #extend file name rm $backuppath/lastweek/* -R mkdir lastweek mv $backuppath/data-* $backuppath/lastweek/fi# Backup the files using tar.filename=$(date +%u-%a-%Y%m%d)tar -zcf $backuppath/$filename $fullbackup.tar.gz -g

# Print end status message.echoecho "Backup finished"dateelse if [ $bktype -gt 2 ]; thenecho "Invalid input"exit 1

fi

PERL scripts should be written to run under Linux/OSX

1: Write a Perl script that will notify a user if they have received email. Thescript should be run under cron at specific intervals and return the fromaddress, subject and date/time email was received in a readable format.

Answer:

#!/usr/bin/perluse strict;use Mysql;use Mail::POP3Client;

sub DoAccount($);

my @Accounts;$Accounts[0] = {'Name' => '[email protected]','Server' => 'mail.curtin.my','Username' => 'allenwong','Password' => '123456'};

MAIN:{foreach my $I (@Accounts){print("Account: $I->{'Name'}\n");DoAccount($I);}}

sub DoAccount($){my ($AN) = @_;my $CreateString;my $Message;my $Sender;my $Recipient;my $Temp;my $TMPFile;$CreateString = "\tUSER => '$AN->{'Username'}',PASSWORD => '$AN->{'Password'}',HOST => '$AN->{'Server'}'";$CreateString .= ",\n\tUSESSL => 'true'" if ($AN->{'SSL'});$CreateString .= ",\n\tPORT => '$AN->{'PORT'}'" if ($AN->{'PORT'});

my $pop = new Mail::POP3Client(eval($CreateString));

print("Logging in....");if (!($pop->Login())){print("Could not connect to account: $AN->{'Name'}: $!\n");return 1;}print("Logged in!\t");

print("Total Messages: " . $pop->Count() . "\n");foreach my $I (1 .. $pop->Count()){$Message = $pop->HeadAndBody($I);

foreach my $Line (split(/\n/, $Message)){if (($Line =~ m/^From:.*$/ig) && (!($Sender))){$Temp = $&;print("Temp: $Temp\n");if ("$Temp" =~ m/[A-Za-z0-9-]+\@[A-Za-z0-9-]+\.[A-Za-z0-9-]+/ig){$Sender = $&;}}last if ($Sender);}if (!($Sender)){print("Error finding sender!\n");next;}do{$TMPFile = "/tmp/MAILSYSTEM-" . rand(1000000000) . ".eml";} while (-e $TMPFile);open(TMP, ">$TMPFile");print TMP $Message;close(TMP);if (system("/server/Mailque/bin/newfilter.pl \"$Sender\" \"exodist\@open-exodus.net\" < $TMPFile")){print("Error sending message!!!\n");}else{$pop->Delete($I);}unlink($TMPFile);}}

2: Write a Perl script that enters a directory anda. Searches all the files in a directory for the occurrence of a stringpassed to the script from the command line.b. It should return the name of the files that contain the string.

Answer:#!/usr/bin/perl

#The filenames from a directory are found in the array @dots. use strict; use warnings;

my $dir = '/etc';

opendir(DIR, $dir) or die $!;

my @dots = grep { /^\./ # Begins with a period && -f "$dir/$_" # and is a file} readdir(DIR);

# Loop through the array printing out the filenames foreach my $file (@dots) { print "$file\n"; } closedir(DIR);

#Print out the name of the file of all the occurrence of a string in the directory

my $line=("omg") # string that we are searching forforeach my $search (@dots) {open(FILE, @dots); # we open each file from command linewhile ($line = ) # we iterate through each line in the file.{print "$line found on $search\n"; # we print out the string on the file we are looking at}close(FILE); # we close the file.}print "Complete.\n";

exit 0;

3: All web pages should meet the W3C standards on accessibility, which includes providing alt tags for all images (a text description of an image). Write a Perl script that parses the source of a web page and displays the text of all alt tags. If an image exists and there is no alt tag text assigned to that image, the user should be notified. Hint: use the curl utility to garb the html.

#!/usr/bin/perl#global varsmy $path_sep = "";

#scan_dirsub scan_dir {my ($dir) = @_;my (@files);chomp $dir;# list all files inside $diropendir( ROOT, $dir ) || die "cant open $dir\n";@files = readdir( ROOT );closedir( ROOT ); FILE: foreach (@files) {# skip the current and the upper directory in the file listingnext FILE if /^\.|\.\.$/;

# build the complete file path$file_path = $dir.$path_sep.$_;if (-d $file_path) {# if the current file is a directory, recursively scan this directory too&scan_dir( $file_path, $last_scan_time );next;}# update only html filesif ($file_path =~ /\.html$/i) {add_alt_tags( $file_path );}}}

#add_alt_tags

sub add_alt_tags {my ($file) = @_;# print out the current file nameprint STDOUT "$file\n";

# read the fileopen( INFILE, "$file" );

for $line (@all) {# match all lines with img tags, but without alt attributesif (($line=~m/()/) && ($2!~m/alt=/)) {# split the matched img tag into two parts, and substitute# the entire tag with an inserted alt attribute...$line =~ s/()/$1 alt=""$2/;}print OUTFILE $line;}close OUTFILE;}

#mainsub main {umask (000);if( $ENV{"OS"} eq "Windows_NT" ) {$path_sep = "\\";}else {$path_sep = "/";}if ($#ARGV==-1) {print STDOUT "Usage: $0 \n";exit 1;}scan_dir( $ARGV[0] );}&main;exit;