BASH 1: 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 message containing this ID.
iii) Create a private group for this user, checking the /etc/group file. Print a message 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, else exit printing a message), expiration date for t his account, extra groups of which 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 user's home directory directory (with correct permissions!); permissions!); add the user to the desired secondary groups. groups.
vi) Set the password for this user to a default known string.
Answer : #!/bin/bash # Script to add a user to Linux system HOME_BASE=”/home/” SHELL=”/bin/bash” read -p -p “Username:” USER read -s -p -p “Password:” PASSWORD egrep -w -w “^$USER” /etc/passwd >/dev/null if [ $# -ne 1 ] echo "Command arguement cannot be more than one or less!"
exit 1 else if [ $? -eq 0 ]; then echo "$username exists!" exit 1 else PASS=$(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!\n” fi
2: Write a script called homebackup that automates tar so the person executing the script always uses the desired options (cvp) and backup destination 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 hold the backup.
iii) Ask the user whether a full or an incremental backup is wanted. If the user does not have a full backup file yet, print a message that a full backup will be taken. In case of an incremental backup, only do this if the full backup is not older than a week.
iv) Compress the backup using any compression tool. Inform t he user that the script is doing this, because it might take some time, during which the user might start worrying if no output appears on the screen.
v) Print a message informing the user about the size of the compressed
backup.
#!/bin/sh if [ $# -ne 0 ] echo "No Command arguement can be present at this moment!" exit 1 fi # 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 1 fi # 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 ]; then echo "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 date if [ "$(date +%a)" = "Mon" && $bktype -eq 2 ]; then ckdate=$(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. echo echo "Backup finished" date else if [ $bktype -gt 2 ]; then echo "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. The script should be run under cron at specific intervals and return the “from address”, subject and date/time email was received in a readable format.
Answer: #!/usr/bin/perl use 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
exodus.net\" < $TMPFile")) { print("Error sending message!!!\n");
\"$Sender\"
\"exodist\@open-
} else { $pop->Delete($I); } unlink($TMPFile); } }
2: Write a Perl script that enters a directory and a. Searches all the files in a directory for the occurrence of a string passed 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 for foreach my $search (@dots)
{ open(FILE, @dots); # we open each file from command line while ($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 vars my $path_sep = "";
#scan_dir sub scan_dir { my ($dir) = @_; my (@files); chomp $dir; # list all files inside $dir opendir( 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 listing next 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 files if ($file_path =~ /\.html$/i) { add_alt_tags( $file_path ); } } } #add_alt_tags sub add_alt_tags { my ($file) = @_; # print out the current file name print STDOUT "$file\n"; # read the file open( INFILE, "<$file" ); @all = ; close( INFILE ); # reopen it for output open( OUTFILE, ">$file" ); for $line (@all) { # match all lines with img tags, but without alt attributes if (($line=~m/(<\s*img\s+src=)(.*?)(>)/) && ($2!~m/alt=/)) { # split the matched img tag into two parts, and substitute # the entire tag with an inserted alt attribute... $line =~ s/(<\s*img\s+src=.*?)(>)/$1 alt=""$2/; } print OUTFILE $line; } close OUTFILE;
} #main sub main { umask (000); if( $ENV{"OS"} eq "Windows_NT" ) { $path_sep = "\\"; } else { $path_sep = "/"; } if ($#ARGV==-1) { print STDOUT "Usage: $0 \n"; 1; } scan_dir( $ARGV[0] ); } &main; exit;
exit