Linux written examination questions script big homework, shell script advanced homework actual combat&Expect

Linux script exercises big assignment, shell script advanced homework actual combat & Expect

Advanced shell scripting

Claim

  • Write a user management script
  • Script format : ./script_file [-h | -a | -d | -p PASSWORD | -s SHELL] USER_LIST_FILE
  • -a Create users in the user list file , this option or -p together
  • -d delete users in the user list file
  • -p PASSWORD Set the user's unified password , if not specified, the default is redhat
  • -s SHELL Specify the user's default shell , if not specify the default **/bin/bash**
  • -h display help information
  • /root/userlist file content
  • Precautions

Script Parameters disorder can be executed

The script returns different status codes according to different situations

Parameter error can report error

Short option should support continuous writing

Do not display redundant output information

User already exists and needs prompt

Script code

[root@ ~/test/shell 10:31:44]#cat script_file.sh 
#!/bin/bash
help_menu()  										#content of the help menu
{
    
    
	echo "Descreption:Hello!This script is used to manage user!"
	echo "FORMAT:./script_file [-h|-a|-d|-p PASSWORD|-s SHELL] User_List_File"
	echo "		 -a			Create the user"
	echo "		 -d			Delete the user"
	echo "		 -p PASSWORD		Set Password for user"
	echo "		 -h			Get Help_Menu"
	echo "		 -s SHELL		Set Default Shell for user"
	echo "		 PASSWORD		Default:redhat"
	echo "		 SHELL			Default:/bin/bash"
	echo "		 User_List_File		Store the users' name"
} 

set -- `getopt -q ap:s:dh $* |sed "s/'//g"` 		#getopt命令对输入参数格式化
i=0
cmd_flag=(0 0 0 0 0) 			   #configue funtions that we should execute!
passwd="redhat"      										#default password
passwd_flag="no"
shell_path="/bin/bash" 									  #default shell path
addr=""										   #default userlist’path is null

until [ $# -eq 0 ];do				    #循环分析:通过cmd_flag数组记录执行命令顺序
	case $1 in
	-h)
		help_menu											#执行help_menu函数
		shift 1
		[ $# -eq 1 ]&& exit 0	  #假如执行命令后附带只有-h选项,那么执行完后直接退出
		;;						
	-a)
		cmd_flag[$i]="add"
		let i++
		shift 1
		;;
	-d)
		cmd_flag[$i]="delete"
		let i++
		shift 1
		;;
	-p)
		cmd_flag[$i]="passwd"
		let i++
		passwd=$2									   #更新密码为用户输入的密码
		passwd_flag="yes"				     #记录我们使用了新的密码而不是默认密码
		shift 2
		;;	
	-s)	
		cmd_flag[$i]="shell"
		let i++
		shell_path=$2					  #更新默认shell为用户输入的shell路径参数
		shift 2
		;;
	--)
		shift 1
		addr=$1
		shift 1
		break
		;;
	*)
		echo "Error1: use option -h to get help!"
		exit 1
		;;								     
    esac	  
done

										 #userlist地址为空,退出并返回错误状态码
[ "$addr" = "" ] >/dev/null 2>&1 && echo "Error6:empty file_list_path !! " && exit 6
									    #userlist文件不存在,退出并返回错误状态码
[ ! -f "$addr" ] >/dev/null 2>&1 && echo "Error7:file doesn't exist!!" && exit 7
										             #记录userlist文件内容行数
temp1=`cat $addr|wc -l`
						 #userlist文件内容行数为0表示内容为空,退出并返回错误状态码
[ $temp1 -eq 0 ] >/dev/null 2>&1 && echo "Error8:file_list is empty!" && exit 8

         						 #通过顺序遍历cmd_flag数组,判断字段,进行相应操作
for cmd in ${
    
    cmd_flag[@]};do
	case $cmd in 
	add)															#添加用户
		while read username;do
			id $username >/dev/null 2>&1 && echo "Error2:user $username exists!"&& continue
			useradd $username  > /dev/null 2>&1
			echo $passwd | passwd --stdin $username >/dev/null 2>&1
			if [ "$passwd_flag" = "yes" ];then		   #如果有新密码,添加新密码
				echo "user $username added!(have new password)"
				flag_pw=1								  #标志已经添加了新密码
            else										     #否则添加默认密码
				echo "user $username added!(have default password)"
			fi
	        done < $addr
		;;
	passwd)
        [ $flag_pw -eq 1 ] && continue		  #已经添加了新密码就不再进行添加密码
		while read username;do
			! id $username >/dev/null 2>&1 && echo "Error3:user $username doesn't exist!!"&&continue
			echo $passwd | passwd --stdion $username >/dev/null 2>&1
			echo "user $username have new password!"
		done < $addr
		;;
	shell)													   #添加默认shell
		while read username;do
			! id $username > /dev/null 2>&1 &&echo "Error4:user $username donesn't exist!!" && continue		
			usermod -s $shell_path $username >/dev/null 2>&1
			echo "user $username have modified default shell!"
		done < $addr
		;;
	delete)														    #删除用户
		while read username;do
			! id $username > /dev/null 2>&1 && echo "Error5:user $username doesn't exist!!" && continue
			userdel $username > /dev/null 2>&1
			echo "user $username deleted" 
		done < $addr
		;;
	*)
		echo "Bye!"					   #不是上述字段,说明没有可执行选项了成功退出
		break
		;;
        esac
done
exit 0

Script test

  • Test execution file without any options parameters
[root@ ~/test/shell 10:35:47]#./script_file.sh 
Error6:empty file_list_path !!
  • Testing: Help tips
[root@ ~/test/shell 10:35:57]#./script_file.sh -h
Descreption:Hello!This script is used to manage user!
FORMAT:./script_file [-h|-a|-d|-p PASSWORD|-s SHELL] User_List_File
		 -a			Create the user
		 -d			Delete the user
		 -p PASSWORD		Set Password for user
		 -h			Get Help_Menu
		 -s SHELL		Set Default Shell for user
		 PASSWORD		Default:redhat
		 SHELL			Default:/bin/bash
		 User_List_File		Store the users' name
  • Test: Add user option without user list path parameter
[root@ ~/test/shell 10:39:28]#./script_file.sh -a 
Error6:empty file_list_path !! 
  • Test: Add user option, with wrong user list path parameter
[root@ ~/test/shell 10:40:28]#./script_file.sh -a ./hahahhaahahahah
Error7:file doesn't exist!!
  • Test: add user option user list path parameters are correct but the user list is empty file
[root@ ~/test/shell 10:45:18]#cat userlist
[root@ ~/test/shell 10:45:24]#./script_file.sh -a ./userlist
Error8:file_list is empty!
  • View userlist (not empty file)
[root@ ~/test/shell 11:01:12]#cat userlist
k1
k2
k3
  • Test: add a user without setting a new password (the default setting is redhat) and the userlist path is correct and the content is not empty
[root@ ~/test/shell 11:01:23]#./script_file.sh -a ./userlist
user k1 added!(have default password)
user k2 added!(have default password)
user k3 added!(have default password)
Bye!

[root@ ~/test/shell 11:02:22]#./script_file.sh -a ./userlist
Error2:user k1 exists!
Error2:user k2 exists!
Error2:user k3 exists!
Bye!

[root@ ~/test/shell 11:14:38]#cat /etc/passwd |grep '^k' |awk -F: '{print $1 " " $7}'    										#查看添加用户的默认shell:/bin/bash
k1 /bin/bash
k2 /bin/bash
k3 /bin/bash
  • Test: Add users to set a unified new password, and the script option parameters are in order
[root@ ~/test/shell 11:07:43]#./script_file.sh -a -p hehehe ./userlist
user k1 added!(have new password)
user k2 added!(have new password)
user k3 added!(have new password)
Bye!
  • Test: Add users to set a unified new password and the script option parameters are out of order
[root@ ~/test/shell 11:23:43]#./script_file.sh ./userlist -amp hehehe  //含不存在的m选项
user k1 added!(have new password)
user k2 added!(have new password)
user k3 added!(have new password)
Bye!
  • Test: Delete user
[root@ ~/test/shell 11:06:34]#./script_file.sh -d ./userlist
user k1 deleted
user k2 deleted
user k3 deleted
Bye!

[root@ ~/test/shell 11:07:21]#./script_file.sh -d ./userlist
Error5:user k1 doesn't exist!!
Error5:user k2 doesn't exist!!
Error5:user k3 doesn't exist!!
Bye!
  • Test: add users, set the default shell
[root@ ~/test/shell 11:11:21]#./script_file.sh -a -s /sbin/nologin ./userlist
user k1 added!(have default password)
user k2 added!(have default password)
user k3 added!(have default password)
user k1 have modified default shell!
user k2 have modified default shell!
user k3 have modified default shell!
Bye!

[root@ ~/test/shell 11:16:28]#cat /etc/passwd |grep '^k' |awk -F: '{print $1 " " $7}'									      #查看添加用户的默认shell:/sbin/nologin
k1 /sbin/nologin
k2 /sbin/nologin
k3 /sbin/nologin

expect

Claim

  • Simulate ftp login and download files
  • Pre-built ftp server and
  • Copy the file /etc/fstab to the /var/ftp directory in advance

Set up ftp server and copy files

[root@ ~ 04:59:37]#iptables -F						//关闭防火墙
[root@ ~ 05:00:01]#yum install vsftpd				//安装ftp服务器软件
Loaded plugins: fastestmirror
...
Package vsftpd-3.0.2-27.el7.x86_64 already installed and latest version
Nothing to do
[root@ ~ 05:02:40]#cp /etc/fstab /var/ftp		//拷贝文件到ftp服务器默认目录
cp: overwrite ‘/var/ftp/fstab’? y
[root@ ~/test/shell 09:54:52]#useradd -d /var/ftp -s /sbin/nologin ftpuser
useradd: warning: the home directory already exists.	//添加登陆用户
Not copying any file from skel directory into it.
[root@ ~ 05:00:21]#systemctl restart vsftpd				//启动ftp服务器
[root@ ~ 05:02:51]#yum install ftp						//安装ftp服务
Loaded plugins: fastestmirror
...
Package ftp-0.17-67.el7.x86_64 already installed and latest version
Nothing to do											//提示已经安装过了

Script file


[root@ ~/test/shell 04:00:47]#vim ftptest.exp 				#编辑脚本
#!/usr/bin/expect
set user "ftpuser"											#设置用户
set pass "ftpuser"											#设置密码
set ip [lindex $argv 0]										#取位置参数

spawn ftp $ip 												#监控命令输出
expect {
    
    											#捕获字段并执行相应操作
        "Name ($ip:root):" {
    
    								#输入登陆用户名
                send "$user\r"
                exp_continue    							#继续捕获字段
                }   
         "Password:" {
    
    										#输入密码
                send "$pass\r"
                exp_continue
                }   
         "ftp> " {
    
     
                send "ls\r"									#查看目录下文件
                send "get fstab\r"						 #获取ftp文件到本地
                send "bye\r"        						#关闭ftp服务
                }   
}
expect eof 													#捕获到退出信号
send_user "\nAll command finished!\n"	 #在本地shell打印字段,相当于执行echo

Script execution

[root@ ~/test/shell 04:00:47]#chmod 700 ./ftptest.exp		//修改权限	
[root@ ~/test/shell 04:46:26]#./ftptest.exp 192.168.6.128	//执行脚本
spawn ftp 192.168.6.128								//监控命令输出,请求连接
Connected to 192.168.6.128 (192.168.6.128).			//连接成功
220 (vsFTPd 3.0.2)									//220:服务就绪
Name (192.168.6.128:root): ftpuser					//输出用户没
331 Please specify the password.					//331:要求密码
Password:
230 Login successful.								//230:登陆因特网
Remote system type is UNIX.
Using binary mode to transfer files.
ftp> ls												//列出ftp服务器目录下文件
227 Entering Passive Mode (192,168,6,128,221,26).   //227:进入被动模式
150 Here comes the directory listing.				//150:打开连接
-rw-r--r--    1 0        0              46 Jun 30 07:29 aa
-rw-r--r--    1 0        0             545 Aug 08 09:02 fstab
drwxr-xr-x    2 0        0            4096 Apr 01 04:55 pub
226 Directory send OK.								//结束数据连接
ftp> get fstab										//获取ftp文件
local: fstab remote: fstab
227 Entering Passive Mode (192,168,6,128,242,119).	//进入被动迷失
150 Opening BINARY mode data connection for fstab (545 bytes).//150打开连接
226 Transfer complete.								//226:结束数据连接
545 bytes received in 2.3e-05 secs (23695.65 Kbytes/sec)
ftp> bye											//关闭ftp
221 Goodbye.										//221:退出网络

All command finished!								//当前终端打印字段

Guess you like

Origin blog.csdn.net/weixin_31789689/article/details/107893007