当前位置: 首页 > 文档资料 > Shell 中文文档 >

M.2. Writing Scripts

优质
小牛编辑
123浏览
2023-12-01

Write a script to carry out each of the following tasks.

EASY

Home Directory Listing

Perform a recursive directory listing on the user's homedirectory and save the information to a file. Compressthe file, have the script prompt the user to inserta floppy, then press ENTER. Finally,save the file to the floppy.

Converting forloops to whileand untilloops

Convert the for loopsin Example 10-1to whileloops. Hint: store the data in an arrayand step through the arrayelements.

Having already done the "heavy lifting",now convert the loops in the example to untilloops.

Changing the line spacing of a text file

Write a script that reads each line of a target file, thenwrites the line back to stdout, but withan extra blank line following. This has the effect ofdouble-spacingthe file.

Include all necessary code to check whether the scriptgets the necessary command line argument (a filename),and whether the specified file exists.

When the script runs correctly, modify it totriple-spacethe target file.

Finally, write a script to remove all blank lines fromthe target file, single-spacingit.

Backwards Listing

Write a script that echoes itself tostdout, butbackwards.

Automatically Decompressing Files

Given a list of filenames as input, this scriptqueries each target file (parsing the output of thefilecommand) forthe type of compression used on it. Then the scriptautomatically invokes the appropriate decompression command(gunzip, bunzip2,unzip, uncompress,or whatever). If a target file is not compressed, thescript emits a warning message, but takes no other actionon that particular file.

Unique System ID

Generate a "unique"6-digit hexadecimalidentifier for your computer. Do notuse the flawed hostidcommand. Hint: md5sum/etc/passwd, then selectthe first 6 digits of output.

Backup

Archive as a "tarball"(*.tar.gzfile) all the filesin your home directory tree(/home/your-name) that havebeen modified in the last 24 hours. Hint: use find.

Primes

Print (to stdout) all prime numbers between 60000 and63000. The output should be nicely formatted in columns(hint: use printf).

Lottery Numbers

One type of lottery involves picking fivedifferent numbers, in the range of 1 - 50. Write ascript that generates five pseudorandom numbers in thisrange, with no duplicates. Thescript will give the option of echoing the numbers tostdoutor saving them to a file,along with the date and time the particular number setwas generated.

INTERMEDIATE

Integer or String

Write a script functionthat determines if an argument passed to it is an integeror a string. The function will return TRUE (0) ifpassed an integer, and FALSE (1) if passed a string.

Hint: What does the following expression returnwhen $1is notaninteger?

expr $1 + 0

Managing Disk Space

List, one at a time, all files larger than 100K inthe /home/usernamedirectory tree. Give the user the option to delete orcompress the file, then proceed to show the next one. Writeto a logfile the names of all deleted files and thedeletion times.

Removing Inactive Accounts

Inactive accounts on a network waste disk space and maybecome a security risk. Write an administrative script(to be invoked by rootor the cron daemon) that checksfor and deletes user accounts that have not been accessedwithin the last 90 days.

Enforcing Disk Quotas

Write a script for a multi-user system that checks users'disk usage. If a user surpasses the preset limit(100 MB, for example) in her /home/usernamedirectory,then the script will automatically send her a warninge-mail.

The script will use the duandmailcommands. As an option,it will allow setting and enforcing quotas using the quotaand setquotacommands.

Logged in User Information

For all logged in users, show their real names and the timeand date of their last login.

Hint: use who,lastlog,and parse /etc/passwd.

Safe Delete

Write, as a script, a "safe"deletecommand, srm.sh. Filenames passedas command-line arguments to this script are not deleted,but instead gzippedif notalready compressed (use fileto check), then moved to a /home/username/trashdirectory. At invocation, the script checks the"trash"directory for files older than 48hours and deletes them.

Making Change

What is the most efficient way to make change for $1.68,using only coins in common circulations (up to 25c)? It's6 quarters, 1 dime, a nickel, and three cents.

Given any arbitrary command line input in dollars andcents ($*.??), calculate the change, using the minimumnumber of coins. If your home country is not the UnitedStates, you may use your local currency units instead. Thescript will need to parse the command line input, thenchange it to multiples of the smallest monetary unit (centsor whatever). Hint: look at Example 23-8.

Quadratic Equations

Solve a "quadratic"equation of the formAx^2 + Bx + C = 0. Have a script takeas arguments the coefficients, A,B, and C,and return the solutions to four decimal places.

Hint: pipe the coefficients to bc, using the well-known formula,x = ( -B +/- sqrt( B^2 - 4AC ) ) / 2A.

Sum of Matching Numbers

Find the sum of all five-digit numbers (in the range10000 - 99999) containing exactly twoout of the following set of digits: { 4, 5, 6 }. These mayrepeat within the same number, and if so, they count oncefor each occurrence.

Some examples of matching numbers are42057, 74638, and 89515.

Lucky Numbers

A "lucky number" is one whose individual digits addup to 7, in successive additions. For example, 62431 is a"lucky number" (6 + 2 + 4 + 3 + 1 = 16, 1 + 6 = 7). Findall the "lucky numbers" between 1000 and 10000.

Alphabetizing a String

Alphabetize (in ASCII order) an arbitrary stringread from the command line.

Parsing

Parse /etc/passwd, and outputits contents in nice, easy-to-read tabular form.

Logging Logins

Parse /var/log/messagestoproduce a nicely formatted file of user logins and logintimes. The script may need to run as root. (Hint: Searchfor the string "LOGIN.")

Pretty-Printing a Data File

Certain database and spreadsheet packages use save-fileswith comma-separated values(CSVs). Other applications often need to parse thesefiles.

Given a data file with comma-separated fields,of the form:

   1 Jones,Bill,235 S. Williams St.,Denver,CO,80221,(303) 244-7989
   2 Smith,Tom,404 Polk Ave.,Los Angeles,CA,90003,(213) 879-5612
   3 ...

Reformat the data and print it out tostdoutin labeled, evenly-spaced columns.

Justification

Given ASCII text input either fromstdinor a file, adjustthe word spacing to right-justify each line to auser-specified line-width, then send the output tostdout.

Mailing List

Using the mailcommand,write a script that manages a simple mailing list. Thescript automatically e-mails the monthly company newsletter,read from a specified text file, and sends it to all theaddresses on the mailing list, which the script reads fromanother specified file.

Generating Passwords

Generate pseudorandom 8-character passwords, usingcharacters in the ranges [0-9], [A-Z], [a-z]. Each passwordmust contain at least two digits.

Checking for Broken Links

Using lynxwith the-traversaloption, write a script thatchecks a Web site for broken links.

DIFFICULT

Testing Passwords

Write a script to check and validate passwords. The objectis to flag "weak"or easily guessed passwordcandidates.

A trial password will be input to the script as acommand line parameter. To be considered acceptable,a password must meet the following minimum qualifications:

    • Minimum length of 8 characters

    • Must contain at least one numeric character

    • Must contain at least one of the followingnon-alphabetic characters:@,

      #,$,%,

      &,*,+,

      -,=

Optional:

    • Do a dictionary check on every sequence of at leastfour consecutive alphabetic characters in the password undertest. This will eliminate passwords containing embedded"words"found in a standard dictionary.

    • Enable the script to check all the passwords on yoursystem. These may or may not reside in/etc/passwd.

This exercise tests mastery of Regular Expressions.

Logging File Accesses

Log all accesses to the files in /etcduring the course ofa single day. This information should include the filename,user name, and access time. If any alterations to thefiles take place, that should be flagged. Write this dataas neatly formatted records in a logfile.

Monitoring Processes

Write a script to continually monitor all runningprocesses and to keep track of how many child processes eachparent spawns. If a process spawns more than five children,then the script sends an e-mail to the system administrator(or root) with all relevant information, including thetime, PID of the parent, PIDs of the children, etc. Thescript writes a report to a log file every ten minutes.

Strip Comments

Strip all comments from a shell script whose nameis specified on the command line. Note that the "#!line"must not be stripped out.

HTML Conversion

Convert a given text file to HTML. This non-interactivescript automatically inserts all appropriate HTML tags intoa file specified as an argument.

Strip HTML Tags

Strip all HTML tags from a specified HTML file, thenreformat it into lines between 60 and 75 charactersin length. Reset paragraph and block spacing, asappropriate, and convert HTML tables to their approximatetext equivalent.

XML Conversion

Convert an XML file to both HTML and text format.

Chasing Spammers

Write a script that analyzes a spam e-mail by doingDNS lookups on the IP addresses in the headers to identifythe relay hosts as well as the originating ISP. Thescript will forward the unaltered spam message to theresponsible ISPs. Of course, it will be necessary tofilter out your own ISP's IP address,so you don't end up complaining about yourself.

As necessary, use the appropriate network analysis commands.

For some ideas, see Example 12-37and Example A-27.

Optional: Write a script that searches through a batch ofe-mail messages and deletes the spam according to specifiedfilters.

Creating man pages

Write a script that automates the process of creatingman pages.

Given a text file which contains information to beformatted into a man page, thescript will read the file, then invoke the appropriategroffcommands tooutput the corresponding man pageto stdout. The text file containsblocks of information under the standard manpageheadings, i.e., "NAME,""SYNOPSIS,""DESCRIPTION,"etc.

See Example 12-26.

Morse Code

Convert a text file to Morse code. Each character of thetext file will be represented as a corresponding Morsecode group of dots and dashes (underscores), separated bywhitespace from the next. For example, "script"===> "... _._. ._. .. .__. _".

Hex Dump

Do a hex(adecimal) dump on a binary filespecified as an argument. The output should be in neattabular fields, with the first field showing the address,each of the next 8 fields a 4-byte hex number, and the finalfield the ASCII equivalent of the previous 8 fields.

Emulating a Shift Register

Using Example 26-14as an inspiration,write a script that emulates a 64-bit shift register asan array. Implementfunctions to loadthe register,shift left, shiftright, and rotateit. Finally, write a function that interprets the registercontents as eight 8-bit ASCII characters.

Determinant

Solve a 4 x 4 determinant.

Hidden Words

Write a "word-find"puzzle generator,a script that hides 10 input words in a 10 x 10 matrixof random letters. The words may be hidden across, down,or diagonally.

Optional: Write a script that solvesword-find puzzles. To keep this from becoming too difficult,the solution script will find only horizontal and verticalwords. (Hint: Treat each row and column as a string, andsearch for substrings.)

Anagramming

Anagram 4-letter input. For example, theanagrams of wordare:do or rod row word. You may use/usr/share/dict/linux.wordsas thereference list.

"Word Ladders"

A "word ladder"is a sequence of words,with each successive word in the sequence differing fromthe previous one by a single letter.

For example, to "ladder"frommarktovase:

   1 mark --> park --> part --> past --> vast --> vase

Write a script that solves "word ladder"puzzles. Given a starting and an ending word,the script will list all intermediate steps in the"ladder". Note that allwords in the sequence must be "legal."

Fog Index

The "fog index"of a passage of textestimates its reading difficulty, as a number correspondingroughly to a school grade level. For example, a passagewith a fog index of 12 should be comprehensible to anyonewith 12 years of schooling.

The Gunning version of the fog index uses the followingalgorithm.

    1. Choose a section of the text at least100 words in length.

    1. Count the number of sentences (a portion ofa sentence truncated by the boundary of the text sectioncounts as one).

    1. Find the average number of words persentence.

      AVE_WDS_SEN = TOTAL_WORDS / SENTENCES

    1. Count the number of "difficult"words in the segment -- those containing at least3 syllables. Divide this quantity by total words toget the proportion of difficult words.

      PRO_DIFF_WORDS = LONG_WORDS / TOTAL_WORDS

    1. The Gunning fog index is the sum of the above twoquantities, multiplied by 0.4, then rounded to thenearest integer.

      G_FOG_INDEX = int ( 0.4 * ( AVE_WDS_SEN + PRO_DIFF_WORDS ) )

Step 4 is by far the most difficult portion of theexercise. There exist various algorithms for estimatingthe syllable count of a word. A rule-of-thumb formulamight consider the number of letters in a word and thevowel-consonant mix.

A strict interpretation of the Gunning fog index doesnot count compound words and proper nouns as"difficult"words, but this would enormouslycomplicate the script.

Calculating PI using Buffon's Needle

The Eighteenth Century French mathematician de Buffoncame up with a novel experiment. Repeatedly drop aneedle of length "n"onto a wooden floorcomposed of long and narrow parallel boards. The cracksseparating the equal-width floorboards are a fixed distance"d"apart. Keep track of the total drops andthe number of times the needle intersects a crack on thefloor. The ratio of these two quantities turns out to bea fractional multiple of PI.

In the spirit of Example 12-45, write ascript that runs a Monte Carlo simulation of Buffon'sNeedle. To simplify matters, set the needle length equal tothe distance between the cracks, n = d.

Hint: there are actually two critical variables:the distance from the center of the needle to the cracknearest to it, and the angle of the needle to thatcrack. You may use bctohandle the calculations.

Playfair Cipher

Implement the Playfair (Wheatstone) Cipher in ascript.

The Playfair Cipher encrypts text by substitutionof "digrams"(2-letter groupings). It istraditional to use a 5 x 5 letter scrambled-alphabetkey squarefor the encryption anddecryption.

   1    C O D E S
   2    A B F G H
   3    I K L M N
   4    P Q R T U
   5    V W X Y Z
   6
   7 Each letter of the alphabet appears once, except "I" also represents
   8 "J". The arbitrarily chosen key word, "CODES" comes first, then all
   9 the rest of the alphabet, in order from left to right, skipping letters
  10 already used.
  11
  12 To encrypt, separate the plaintext message into digrams (2-letter
  13 groups). If a group has two identical letters, delete the second, and
  14 form a new group. If there is a single letter left over at the end,
  15 insert a "null" character, typically an "X."
  16
  17 THIS IS A TOP SECRET MESSAGE
  18
  19 TH IS IS AT OP SE CR ET ME SA GE
  20
  21 For each digram, there are three possibilities.
  22 ----------------------------------------------
  23 1) Both letters will be on the same row of the key square
  24    For each letter, substitute the one immediately to the right, in that
  25    row. If necessary, wrap around left to the beginning of the row.
  26
  27 or
  28
  29 2) Both letters will be in the same column of the key square
  30    For each letter, substitute the one immediately below it, in that
  31    row. If necessary, wrap around to the top of the column.
  32
  33 or
  34
  35 3) Both letters will form the corners of a rectangle within the key
  36    square. For each letter, substitute the one on the other corner the
  37    rectangle which lies on the same row.
  38
  39
  40 The "TH" digram falls under case #3.
  41 G H
  42 M N
  43 T U           (Rectangle with "T" and "H" at corners)
  44
  45 T --> U
  46 H --> G
  47
  48
  49 The "SE" digram falls under case #1.
  50 C O D E S     (Row containing "S" and "E")
  51
  52 S --> C  (wraps around left to beginning of row)
  53 E --> S
  54
  55 =========================================================================
  56
  57 To decrypt encrypted text, reverse the above procedure under cases #1
  58 and #2 (move in opposite direction for substitution). Under case #3,
  59 just take the remaining two corners of the rectangle.
  60
  61
  62 Helen Fouche Gaines' classic work, ELEMENTARY CRYPTANALYSIS (1939), gives a
  63 fairly detailed rundown on the Playfair Cipher and its solution methods.

This script will have three main sections

  1. Generating the "key square",based on a user-input keyword.

  1. Encrypting a "plaintext"message.

  1. Decrypting encryptedtext.

The script will make extensive use of arraysand functions.

--

Please do not send the author your solutions to theseexercises. There are better ways to impress him with yourcleverness, such as submitting bugfixes and suggestions forimproving this book.