Linux shell script God-general test case

Source: Internet
Author: User
Tags stdin disk usage

I do not know the shell script, the work of the shell script, all can only gig, search Niang 1.1 point of writing. A good case was seen during the search. You can refer to it for a moment. Will certainly be able to use in the future.

Disclaimer This article is reproduced to http://www.educity.cn/linux/1241314.html

Script 1: Write a login welcome script for the root user:

1, with the VI command in the/root directory is a new script file welcome.sh, the contents are as follows:

  

2. Add the Execute (x) permission to the welcome.sh file using the chmod command

3. Modify the/root/.bash_profile file to invoke the welcome.sh script every time the root user logs on to the system

#vi/root/.bash_profile Add the following:

  

4. Authentication: Log back in with the root user to verify the output information of the Welcome script

Script 2: Scripting to start, stop, and display system service status:

1, with the VI command in the/root/bin directory is a new script file status used to view the state of the Crond service, the contents are as follows:

  

Set X Permissions

The script file stop and start are similar to status and can be modified slightly.

Script 3: Write the health monitoring script/opt/monitor.sh, which records information such as CPU load, memory and swap space, disk space, recent user logins, and time information.

1, with the VI command in the/OPT directory is a new script file monitor.sh, the contents are as follows:

#!/bin/bash

Mkdir-p/var/log/runrec

Recfile= "/var/log/runrec/running.today"

Rectime= ' date + '%y-%m-%d%h:%m '

Loadrec= ' uptime '

Memrec= ' Free-m '

Diskrec= ' Df-ht '

lastloginrec= ' Last-n 20 '

echo "++++++++++++++++++++++++++++++++++++++++++++++++++++++++

Record Time: $RecTime

CPU Load Information: $LOADREC

Memory Information: $MemRec

Disk Usage Information: $DiskRec

Last Login the users record: $LastLoginRec >> $RecFile

2. Add the Execute (x) permission to the monitor.sh file using the chmod command

3. Whether the test script can run properly and output the correct information

4, set the scheduled task, request every 15 minutes to hold the monitor.sh script, and confirm that the Crond service has been started.

To create a scheduled task:

#crontab –e content is as follows

*/15 * * * */opt/monitor.sh

View the Crond service status and set the Crond boot automatically.

#service crondStatus

#chkconfig--level Crond on

Script 1: Writing a shell script monitoring host

1, with the VI command in the/root directory is a new script file sysmon.sh, the contents are as follows:

  

Report:

A: Use the DF command to extract the disk occupancy of the root partition, as shown in:

Use the df-h command to view disk partition usage where the used space for the root partition is 10%

  

Use the command as in to filter the disk's used space

  

B: Use the Mpstat command to extract CPU usage (to make sure that the Sysstat package is installed). As shown in: Where%idle represents the percentage of CPU idle time

  

Use the command as in to get the CPU used space and assign the value to the variable CUG

  

C: Use the free command to view memory usage. Where the red line indicates free memory.

  

Use the command as in to get memory usage and assign a value to the variable mug

  

2. Add the Execute (x) permission to the sysmon.sh file using the chmod command

3. Test the execution of sysmon.sh scripts

A: Configure the DNS service to resolve MX and a records for mail servers

B: Modify the/etc/nf file to point to the DNS server address

C: Configure the mail server

If it is a postfix server, configure the following:

  

Modify the Main.cf file with the following modified content:

  

Restart the Postfix service. Concurrent test messages.

D: Verify that the mail server is available, then lower the monitoring threshold and execute the sysmon.sh script to test

E: Check the name of the mailbox, confirm the warning message content

  

The contents of the message are as follows:

  

4, set up crontab scheduled tasks, every half minor with a sysmon.sh script program

  

Restart the Crond service.

Script 2: Writing a shell script (mkbak.sh) prompts the user to specify the path to the backup directory, and if the directory is already present, skips after displaying the message, otherwise the directory is created after displaying the appropriate information.

  

Script 3: The Scripting Program (CHKDBSVR.SH) is used to monitor the running state of the system service mysqld every 5 minutes, and if the mysqld process is found to have stopped, append write log information (including the time of day) to the/var/log/messages file. Restart the MYSQLD service, otherwise do nothing

  

Script 4: Scripting is used to monitor the running state of the system service httpd, which requires the following

Log information is logged in the "/var/log/htmon.log" file when the service status is abnormal.

Automatically restarts the HTTPD service with an abnormal state. If restarting the HTTPD service fails, test attempts to restart the server host

Perform a monitoring mission every 15 minutes from Monday to Friday, combined with Crond scheduled tasks

1, create the script htmon.sh in the/OPT directory, the script content is as follows

#! /bin/bash

/sbin/service httpdstatus &>/dev/null

If [$?-ne 0]; Then

echo "' Date '" >>/var/log/htmon.log

/sbin/service httpd Restart

/sbin/service httpd Status &>/dev/null

If [$?-ne 0]; Then

/sbin/chkconfig--level 2345 httpd on

/sbin/shutdown-r now

Fi

Fi

2. Create Crontab Scheduled Tasks

*/15 * * * */opt/htmon.sh

Script 1: Write a script named getarp.sh that logs the MAC addresses of each host in the LAN. Save to/Etc/ether file, if this file already exists, you should make a backup first. Line one record, the 1th column is the IP address, and the 2nd column corresponds to the MAC address.

Analysis:

Assuming that the network segment to be scanned is 192.168.4.0, assign the 192.168.4. To the variable nadd as a prefix for the detection address

Use the "Arping-c 2-w 1 detected host IP" command to send an ARP request to record the MAC address

  

Use the while loop to detect the target master and record the MAC address, where the host address is detected as

1, use VI to create a script called getarp.sh, the content is as follows:

#!/bin/bash

Nadd= "192.168.4."

File= "/etc/ethers"

[-F $FILE] &&/bin/cp-f $FILE $FILE. Old

Hadd=1

while[$HADD-lt 4]

Do

Arping-c 2-w 1 ${nadd}${hadd} &>/dev/null

If [$?-eq 0]; Then

Arp-n | grep ${nadd}${hadd} | awk ' {print$1,$3} ' >> $FILE

Fi

Let hadd++

Done

2. Add x permission to script getarp.sh

3. Execute the script to view the detected Mac information

Script 2: Write a script scanhost.sh, check which hosts have the anonymous FPT service turned on, scan the object forall IP addresses in the/etc/ethers file, scan the port number

Environment Description: Assume that the 192.168.4.2 host is an anonymous access FTP. 192.168.4.3 FTP for non-anonymous visits.

Create a scan file/etc/ethers with the following contents:

  

Here wget download tool: Wget ftp://IP/

1, use VI to create a script called scanhost.sh, the content is as follows:

#!/bin/bash

target=$ (awk ' {print '} '/etc/ethers)

echo "Follow is anonymous FTP server:"

Forip in $TARGET

Do

Wget–t 3-t 3 ftp://$IP/&>/dev/null

If [$?-eq 0]; Then

Echo $IP

Fi

Done

Parameter hint:-T connection timeout time;-T connection retry count

2. Add x permission to script getarp.sh

3. Execute the script to view the scanned information

Script 3: Total amountof space occupied by all NF profiles in the COMPUTE/etc/directory

Create a script named confsize.sh with VI, which reads as follows:

#!/bin/bash

sizenums=$ (Ls-l $ (find/etc/-type f-a-name nf) | awk ' {print $} ')

Total=0

Fori in $sizenums

Do

total=$ (expr $total + $i)

Done

echo "Total size of conf files: $total bytes."

Script 4: Write a script chkfileown.sh, for the system that uses bash as the login shell, check their number of files in the/OPT directory and list the specific values and corresponding user accounts

1, use VI to create a script called chkfileown.sh, the content is as follows:

#!/bin/bash

Dir= "/opt/"

validusers=$ (grep "bash$"/etc/passwd | awk-f: ' {print $} ')

Forusername in $validusers

Do

num=$ (Find $DIR-user $username | wc-l)

echo "$username have $num files."

Done

2. Add x permission to script getarp.sh

3. Execute the script to view the information after execution (note: If there are no files in the/opt directory, you can create some test files beforehand)

Script 5: Scripting is used to add users in bulk, with the following requirements:

Requires interactivity, and when the administrator executes the script, it can be prompted to specify the number of users to add (less than 100), the user name prefix, and the ability to set the expiration time of these user accounts, the initial password.

User name numbers use a uniform two-digit number, such as "01", "02", "03", instead of "1", "2", and "3" forms.

Write the corresponding batch deletion in addition to the user script, to be able to specify the user name prefix through the command line parameters, after executing the script to delete all the user accounts using the prefix, but to prevent the deletion of the root user.

To add a user script in bulk:

1, Batch add user script myuadd.sh content as follows:

#!/bin/bash

Read-p "Input nu <1-99>:" Nu

Read-p "input name:" Name

Read-p "Input date <yyyy-mm-dd>:" Date

Read-p "Input password:" Password

A=1

if[$nu-LT 100]

Then

while[$a-le $nu]

Do

If [$a-lt 10]

Then

Useradd-e $date "$name" 0 "$a"

echo "$password" | Passwd--stdin "$name" 0 "$a" &>/dev/null

Else

Useradd-e $date "$name" "$a"

echo "$password" | Passwd--stdin "$name" "$a" &>/dev/null

Fi

A= ' expr$a + 1 '

Done

Fi

2. Add x permission to script myuadd.sh

3. Execute script myuadd.sh, add user

4. Verify the result: See/etc/passwd file added new user

To delete a user script in bulk:

1, bulk Delete user script myudel.sh content as follows:

#!/bin/bash

if[$#-le 0]; Then

echo "error:the prefix of users has notbe specified."

echo "Usage:$0 Nameprefix"

Exit 1

Fi

Tarjcvf/root/f.tar.gz/etc/passwd/etc/shadow/etc/group &>/dev/null

Tobedel= ' grep ' $ '/etc/passwd | Cut-d ":"-F 1 | Grep-v "Root"

Foru in $tobedel

Do

Userdel-r $u &>/dev/null

Done

2. Add x permission to script myudel.sh

3, execute the script myudel.sh, delete the user. such as myudel.shcaiwu03 or myudel.sh Caiwu

4. Verify the results: seeIf the deleted user is still present in the etc/passwd file.

Report:

We can use the ENV or Export command to view environment variables, use the SET command to view all variables (including environment variables and custom variables), and use the unset command to delete variables

Most versions of the Linux system have a random number generator, which is the/dev/random file. Random numbers can be randomly obtained by $random the system environment variables associated with this random number file . In bash, the contents of this random variable are between 0--32767, (Man bash, search for random can see the description) so as long as the Echo $RANDOM, the system will randomly take out a value between 0--32767. For example, if you want a random number between 0-9, you can declare a numeric type with declare

  

Or

  

Linux shell script God-general test case

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.