shell编程面试必会30题

来源说明:《跟老男孩学Linux运维》Shell编程实战

说明:对于每个脚本,用shell编程的同时,我再用python实现,达到同时熟悉两种脚本语言的目的。由于初学python,有问题还请大家斧正。


面试题1:批量生产随机字符文件

用shell实现

代码

root@vmUbu:/home/dell/shell#vimcreat_ten_htmlfile.sh
#!/bin/bash

#Date:2017-8-25
#Author:XianWei

Path=/tmp/shelltmp
[-d"$Path"]||mkdir-p$Path#如果测试结果为假,就执行mkdir语句
cd$Path
for((i=0;i<10;i++))#循环执行10次
do
namepre=`date+%s|md5sum|tr-dc"a-z"`#生成随机的10个字母
namepost='_oldboy.html'#文件名的后缀
filename=${namepre}${namepost}#字符串连接
touch$filename
echo"$filenamehavebeencreated."
sleep1

done&
wait


测试

root@vmUbu:/home/dell/shell#./creat_ten_htmlfile.sh
adcaeeafbc_oldboy.htmlhavebeencreated.
ecbdeabdaedceb_oldboy.htmlhavebeencreated.
edffdbddee_oldboy.htmlhavebeencreated.
beadcabbbdcbdb_oldboy.htmlhavebeencreated.
fcaadeaedafbc_oldboy.htmlhavebeencreated.
adddadbc_oldboy.htmlhavebeencreated.
bcadafebdabe_oldboy.htmlhavebeencreated.
deffebcd_oldboy.htmlhavebeencreated.
fafbbcdcfcfecef_oldboy.htmlhavebeencreated.
fbfdedccbcc_oldboy.htmlhavebeencreated.
root@vmUbu:/home/dell/shell#
root@vmUbu:/home/dell/shell#ll/tmp/shelltmp/
total8
drwxr-xr-x2rootroot4096Aug2507:53./
drwxrwxrwt15rootroot4096Aug2508:05../
-rw-r--r--1rootroot0Aug2507:53adcaeeafbc_oldboy.html
-rw-r--r--1rootroot0Aug2507:53adddadbc_oldboy.html
-rw-r--r--1rootroot0Aug2507:53bcadafebdabe_oldboy.html
-rw-r--r--1rootroot0Aug2507:53beadcabbbdcbdb_oldboy.html
-rw-r--r--1rootroot0Aug2507:53deffebcd_oldboy.html
-rw-r--r--1rootroot0Aug2507:53ecbdeabdaedceb_oldboy.html
-rw-r--r--1rootroot0Aug2507:53edffdbddee_oldboy.html
-rw-r--r--1rootroot0Aug2507:53fafbbcdcfcfecef_oldboy.html
-rw-r--r--1rootroot0Aug2507:53fbfdedccbcc_oldboy.html
-rw-r--r--1rootroot0Aug2507:53fcaadeaedafbc_oldboy.html


总结:

考察知识点:

1)生成随机数的方法

2)字符串连接的方法


使用Python实现

代码

#encoding:utf-8

importrandom
importos

defget10char():#create10randomcharactors
seed="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMnopQRSTUVWXYZ"
sa=[]
foriinxrange(10):
sa.append(random.choice(seed))
salt=''.join(sa)

returnsalt

defcreatefile(name):
path="/tmp/shelltmp/"#checkwhetherthedirisexists,ifnotcreateit
ifos.path.exists(path)!=True:
os.mkdir(path)

pathAndName=path+name
withopen(pathAndName,"wb")asf:#createfile
pass
ifos.path.exists(pathAndName):
print"%shavebeencreated"%name#printtheresult
else:
print"createfileFailed,Pleasecheckit."


defmain():
foriinxrange(10):#loop10timestocreate10file
filename=get10char()+"_oldboy.html"
createfile(filename)


if__name__=="__main__":
main()



面试题2:将面试题1中的字符串oldboy全部改为oldgirl


方法一:使用awk生成所需命令,再用bash执行

代码和测试:

root@vmUbu:/tmp/shelltmp#foriin`ls/tmp/shelltmp`;doecho$i|awk-F"_"'{print"mv"$0""$1"_oldgirl.html"}'|bash;done

root@vmUbu:/tmp/shelltmp#ls
adcaeeafbc_oldgirl.htmlbeadcabbbdcbdb_oldgirl.htmledffdbddee_oldgirl.htmlfcaadeaedafbc_oldgirl.html
adddadbc_oldgirl.htmldeffebcd_oldgirl.htmlfafbbcdcfcfecef_oldgirl.html
bcadafebdabe_oldgirl.htmlecbdeabdaedceb_oldgirl.htmlfbfdedccbcc_oldgirl.html
root@vmUbu:/tmp/shelltmp#


方法2:使用sed替换文件名,再用mv修改文件

代码

#!/bin/bash

#Date:2017-8-25
#Author:XianWei

Path=/tmp/shelltmp
[-d"$Path"]||exit0#如果测试结果为假,就执行mkdir语句
cd$Path

foroldfilein`ls$Path/|grepoldboy`
do
newfile=`echo$oldfile|seds/oldboy/oldgirl/g`#生成新的文件名
mv$oldfile$newfile

done&
wait

测试

root@vmUbu:/home/dell/shell#python1_creat_ten_htmlfile.py
WKfqYfUprf_oldboy.htmlhavebeencreated
QplbhAZVZA_oldboy.htmlhavebeencreated
jmkkmepTfD_oldboy.htmlhavebeencreated
IAeFZLHzOj_oldboy.htmlhavebeencreated
DwWbMsCqtN_oldboy.htmlhavebeencreated
ZgAVXNCyLQ_oldboy.htmlhavebeencreated
DBENsfnZpv_oldboy.htmlhavebeencreated
PveegnMyBo_oldboy.htmlhavebeencreated
MpReSrwXJr_oldboy.htmlhavebeencreated
SWWFrkYhdi_oldboy.htmlhavebeencreated
root@vmUbu:/home/dell/shell#
root@vmUbu:/home/dell/shell#ll/tmp/shelltmp/
total8
drwxr-xr-x2rootroot4096Aug2511:32./
drwxrwxrwt16rootroot4096Aug2511:32../
-rw-r--r--1rootroot0Aug2511:32DBENsfnZpv_oldboy.html
-rw-r--r--1rootroot0Aug2511:32DwWbMsCqtN_oldboy.html
-rw-r--r--1rootroot0Aug2511:32IAeFZLHzOj_oldboy.html
-rw-r--r--1rootroot0Aug2511:32jmkkmepTfD_oldboy.html
-rw-r--r--1rootroot0Aug2511:32MpReSrwXJr_oldboy.html
-rw-r--r--1rootroot0Aug2511:32PveegnMyBo_oldboy.html
-rw-r--r--1rootroot0Aug2511:32QplbhAZVZA_oldboy.html
-rw-r--r--1rootroot0Aug2511:32SWWFrkYhdi_oldboy.html
-rw-r--r--1rootroot0Aug2511:32WKfqYfUprf_oldboy.html
-rw-r--r--1rootroot0Aug2511:32ZgAVXNCyLQ_oldboy.html
root@vmUbu:/home/dell/shell#


python实现

代码

#encoding:utf-8

importrandom
importos
importsys


defmain():
path="/tmp/shelltmp/"
ifos.path.exists(path)!=True:#checkthedirwhetherexists
print"%snotexists,checkit."%path
sys.exit(1)

forroot,dir,fileinos.walk(path):#putthedestfileintoalist
pass
foroldfilenameinfile:
ifoldfilename.split("_")[1]=="oldboy.html":#iffilenameincludestrings"oldboy",changeitsname
newfilename=oldfilename.split("_")[0]+"_oldgirl.html"
os.rename(path+oldfilename,path+newfilename)#changename
ifos.path.exists(path+newfilename):#printtheresult
print"%shavebeenchangenameto%s"%(oldfilename,newfilename)
else:
print"%schangednameFailed."%(oldfilename)


if__name__=="__main__":
main()

测试

root@vmUbu:/home/dell/shell#ls/tmp/shelltmp/
COFoqgRped_oldboy.htmlFnlInKOFDD_oldboy.htmlKraoAAesrC_oldboy.htmlLFCkswpeJc_oldboy.htmlRXwWPTAYTF_oldboy.html
dxTHbQyYyZ_oldboy.htmlickDGJUVgD_oldboy.htmlLBblatnuRW_oldboy.htmlReFkjxYZjO_oldboy.htmltKwmVefsCP_oldboy.html
root@vmUbu:/home/dell/shell#python2_change_name.py
LFCkswpeJc_oldboy.htmlhavebeenchangenametoLFCkswpeJc_oldgirl.html
dxTHbQyYyZ_oldboy.htmlhavebeenchangenametodxTHbQyYyZ_oldgirl.html
FnlInKOFDD_oldboy.htmlhavebeenchangenametoFnlInKOFDD_oldgirl.html
RXwWPTAYTF_oldboy.htmlhavebeenchangenametoRXwWPTAYTF_oldgirl.html
COFoqgRped_oldboy.htmlhavebeenchangenametoCOFoqgRped_oldgirl.html
ReFkjxYZjO_oldboy.htmlhavebeenchangenametoReFkjxYZjO_oldgirl.html
LBblatnuRW_oldboy.htmlhavebeenchangenametoLBblatnuRW_oldgirl.html
tKwmVefsCP_oldboy.htmlhavebeenchangenametotKwmVefsCP_oldgirl.html
KraoAAesrC_oldboy.htmlhavebeenchangenametoKraoAAesrC_oldgirl.html
ickDGJUVgD_oldboy.htmlhavebeenchangenametoickDGJUVgD_oldgirl.html
root@vmUbu:/home/dell/shell#ls/tmp/shelltmp/
COFoqgRped_oldgirl.htmlFnlInKOFDD_oldgirl.htmlKraoAAesrC_oldgirl.htmlLFCkswpeJc_oldgirl.htmlRXwWPTAYTF_oldgirl.html
dxTHbQyYyZ_oldgirl.htmlickDGJUVgD_oldgirl.htmlLBblatnuRW_oldgirl.htmlReFkjxYZjO_oldgirl.htmltKwmVefsCP_oldgirl.html
root@vmUbu:/home/dell/shell#



面试题3:批量创建用户和密码


代码

root@vmUbu:/home/dell/shell#vim3_create_user.sh

#!/bin/bash

#Date:2017-8-25
#Author:XianWei
#createtenusersinbulk


for((i=0;i<=10;i++))
do
username="oldboy${i}"#cannotusesymbol''
password=`tr-dc"a-zA-Z0-9"</dev/urandom|head-c8`#create8randomcharactors
#echo$username
useradd$username
echo$username:$password|chpasswd#changepasswd.ifos=centos,usepasswd--stdin
#echo${username}""${password}
echo${username}""${password}>>passwd.txt#recordtheusernameandit'spassword
done


测试

root@vmUbu:/home/dell/shell#./3_create_user.sh
root@vmUbu:/home/dell/shell#cat/etc/passwd
......
hello:x:1001:1001::/home/hello:
oldboy0:x:1002:1002::/home/oldboy0:
oldboy1:x:1003:1003::/home/oldboy1:
oldboy2:x:1004:1004::/home/oldboy2:
oldboy3:x:1005:1005::/home/oldboy3:
oldboy4:x:1006:1006::/home/oldboy4:
oldboy5:x:1007:1007::/home/oldboy5:
oldboy6:x:1008:1008::/home/oldboy6:
oldboy7:x:1009:1009::/home/oldboy7:
oldboy8:x:1010:1010::/home/oldboy8:
oldboy9:x:1011:1011::/home/oldboy9:
oldboy10:x:1012:1012::/home/oldboy10:
root@vmUbu:/home/dell/shell#

#查看密码文件
root@vmUbu:/home/dell/shell#catpasswd.txt
oldboy0Je28ZqTi
oldboy1LcA5AX3u
oldboy2QF36POh2
oldboy35BMoklFp
oldboy418slv8fB
oldboy58eIVWck3
oldboy6ZuWQcqjT
oldboy7lSeahDHM
oldboy8XvqBiFPA
oldboy9VNc8fLZC
oldboy10zdbruc2S


python实现

代码

#encoding:utf-8

'''
#date:2017-8-26
#Author:XianWeifromChengDu
#scripteFunction:createusersandsetitspasswordinbulk
'''
importrandom
importos
importsys
importsubprocess
importrandom

defget_passwd(n):
passwdlist=[]
seed="abcdefghijkmnopqrstuvwxyz"
forjinxrange(n):
passwdlist.append(random.choice(seed))
passwd="".join(passwdlist)
returnpasswd

defcreate_user(user):
create_user_cmd='useradd%s'%user
p=subprocess.Popen(args=create_user_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,close_fds=True)
returncode=p.wait()
ifreturncode==0:
print"useradd%ssuccussful"%user
password=get_passwd(8)
set_passwd_cmd='echo%s:%s|chpasswd'%(user,password)
p2=subprocess.Popen(args=set_passwd_cmd,close_fds=True)
returncode_p2=p2.wait()
ifreturncode_p2==0:
print"%ssetpasswordsuccussful.itspassword:%s"%(user,password)
else:
print"sorry,setpasswordFailed!"
else:
print"useraddFailed."
sys.exit(1)

defmain():
userlist=[]
foriinxrange(1,11):
userlist.append("oldgirl"+str(i))
foruserinuserlist:
create_user(user)


if__name__=="__main__":
main()


测试

root@vmUbu:/home/dell/shell#python3_create_user.pyuseraddoldgirl1succussful
oldgirl1setpasswordsuccussful.itspassword:qtcvheyq
useraddoldgirl2succussful
oldgirl2setpasswordsuccussful.itspassword:wnaecfxu
useraddoldgirl3succussful
oldgirl3setpasswordsuccussful.itspassword:wpxwtcvv
useraddoldgirl4succussful
oldgirl4setpasswordsuccussful.itspassword:cpquxwzd
useraddoldgirl5succussful
dgirl5setpasswordsuccussful.itspassword:gdtmttug
useraddoldgirl6succussful
oldgirl6setpasswordsuccussful.itspassword:eznjdjow
useraddoldgirl7succussful
oldgirl7setpasswordsuccussful.itspassword:eysxegpu
useraddoldgirl8succussful
oldgirl8setpasswordsuccussful.itspassword:yhdkrdyb
useraddoldgirl9succussful
oldgirl9setpasswordsuccussful.itspassword:omytwhdh
useraddoldgirl10succussful
oldgirl10setpasswordsuccussful.itspassword:zpenokqg
root@vmUbu:/home/dell/shell#
root@vmUbu:/home/dell/shell#cat/etc/passwd|grepoldgirl
oldgirl1:x:1013:1013::/home/oldgirl1:
oldgirl2:x:1014:1014::/home/oldgirl2:
oldgirl3:x:1015:1015::/home/oldgirl3:
oldgirl4:x:1016:1016::/home/oldgirl4:
oldgirl5:x:1017:1017::/home/oldgirl5:
oldgirl6:x:1018:1018::/home/oldgirl6:
oldgirl7:x:1019:1019::/home/oldgirl7:
oldgirl8:x:1020:1020::/home/oldgirl8:
oldgirl9:x:1021:1021::/home/oldgirl9:
oldgirl10:x:1022:1022::/home/oldgirl10:
root@vmUbu:/home/dell/shell#


面试题4:扫描网络内存活主机


代码

#!/bin/bash

#Date:2017-8-26
#Author:XianWei
#checktheserverwhetherisalive

ippre='192.168.142.'
cmd='ping-c2'

for((i=0;i<=20;i++))
do
{
$cmd$ippre$i>/dev/null2&>1
if[$?-eq0]
then
echo"$ippre$iisok"
else
echo"$ippre$iisdown"
fi
}&#parallelprogress
done
wait#letparentprogresswaitallchildprogress

测试

root@vmUbu:/home/dell/shell#time./4_ping_host.sh
192.168.142.0isdown
192.168.142.2isok
192.168.142.11isdown
192.168.142.20isdown
192.168.142.4isdown
192.168.142.12isdown
192.168.142.3isdown
192.168.142.9isdown
192.168.142.18isdown
192.168.142.5isdown
192.168.142.15isdown
192.168.142.13isdown
192.168.142.16isdown
192.168.142.17isdown
192.168.142.10isdown
192.168.142.14isdown
192.168.142.6isdown
192.168.142.19isdown
192.168.142.1isdown
192.168.142.7isdown
192.168.142.8isdown

real0m11.229s
user0m0.024s
sys0m0.720s


python实现

代码

#encoding:utf-8

'''
#date:2017-8-26
#Author:XianWeifromChengDu
#scripteFunction:checkipwhetherisalivedinbulk
'''
importrandom
importos
importsys
importsubprocess
importrandom
importplatform
importre
fromthreadingimportThread
fromQueueimportQueue
importtime


defcheck_ip(ipaddr):
#函数用于检测IP地址合法性。来源:http://blog.csdn.net/jbxue123/article/details/23156011
addr=ipaddr.strip().split('.')#切割IP地址为一个列表
#printaddr
iflen(addr)!=4:#切割后列表必须有4个参数
print"%s,ipaddressisillegal!"%ipaddr
returnFalse
foriinrange(4):
try:
addr[i]=int(addr[i])#每个参数必须为数字,否则校验失败
except:
print"%s,ipaddressisillegal!"%ipaddr
returnFalse
ifaddr[i]<=255andaddr[i]>=0:#每个参数值必须在0-255之间
pass
else:
print"%s,ipaddressisillegal!"%ipaddr
returnFalse
#print"checkipaddresssuccess!"
returnTrue


defping_host(ip):
ifcheck_ip(ip)==False:#检测IP合法性
sys.exit(1)
platformOfSystem=platform.system()#根据平台,设置ping命令
if(platformOfSystem=="Windows"):
cmd="ping-n2%s"%(ip)
if(platformOfSystem=="Linux"):
cmd="ping-c2%s"%(ip)

res=os.popen(cmd)


if(platform.system()=="Windows"):
if(re.findall("Lost=2",res.read()).__len__()!=0):
print"%sisdown."%ip
else:
print"%sisOK."%ip

if(platform.system()=="Linux"):
pingResult=re.findall("DestinationHostUnreachable",res.read())
if(pingResult.__len__()!=0):
print"%sisdown."%ip
else:
print"%sisOK."%ip

defmain():

print"mainthreadingwaiting......"
ip_prefix="192.168.142."#设置ip列表
iplist=[]
n=10
foriinxrange(1,n+1):
iplist.append(ip_prefix+str(i))

tlist=[]
foriinxrange(len(iplist)):#使用多线程ping
t=Thread(target=ping_host,args=(iplist[i],))#将线程加入list
tlist.append(t)

forthreadintlist:#启动所有线程
thread.setDaemon(True)
thread.start()

forthreadintlist:#等待所有线程结束
thread.join()

print"mainthreadingDone"


if__name__=="__main__":
main()

linux平台测试

root@vmUbu:/home/dell/shell#timepython4_ping_host.py
mainthreadingwaiting......
192.168.142.1isOK.
192.168.142.2isOK.
192.168.142.3isdown.
192.168.142.6isdown.
192.168.142.4isdown.
192.168.142.5isdown.
192.168.142.7isdown.
192.168.142.8isdown.
192.168.142.9isdown.
192.168.142.10isdown.
mainthreadingDone

real0m3.166s
user0m0.100s
sys0m0.296s
root@vmUbu:/home/dell/shell#

windows平台测试

C:\Users\Administrator\PycharmProjects\shell_to_python\0826>pythonchangename.py

mainthreadingwaiting......
192.168.142.1isOK.
192.168.142.3isdown.
192.168.142.6isdown.
192.168.142.9isdown.
192.168.142.4isdown.
192.168.142.7isdown.
192.168.142.8isdown.
192.168.142.5isdown.
192.168.142.2isOK.192.168.142.10isdown.

mainthreadingDone


面试题10:比较两个数大小

要求:输入两个数,比较大小并输出结果

代码

#!/bin/bash

#Date:2017-8-27
#Author:XianWei
#作用:输入两个数,比较大小并输出结果


#判断输入的是否为数字
functionjudgenum()
{
	if[$1-gt-99999999]>/dev/null2>&1	#与一个很小的数比较
	then
		echo-n
	else
		echo"Error,Pleaseinputanumber"
		exit
	fi
}

read-p"Pleaseinputthefirstnumber:"num1
judgenum$num1
read-p"Pleaseinputthesecondnumber:"num2
judgenum$num2

letres=$num1-$num2
echo$res

[$res-gt0]&&echo"$num1>$num2"	
[$res-lt0]&&echo"$num1<$num2"	
[$res-eq0]&&echo"$num1=$num2"	

测试

dell@vmUbu:~/shell$bashjudgenum.sh
Pleaseinputthefirstnumber:1
Pleaseinputthesecondnumber:b
Error,Pleaseinputanumber
dell@vmUbu:~/shell$bashjudgenum.sh
Pleaseinputthefirstnumber:a
Error,Pleaseinputanumber
dell@vmUbu:~/shell$
dell@vmUbu:~/shell$
dell@vmUbu:~/shell$
dell@vmUbu:~/shell$bashjudgenum.sh
Pleaseinputthefirstnumber:2
Pleaseinputthesecondnumber:2
2=2
dell@vmUbu:~/shell$bashjudgenum.sh
Pleaseinputthefirstnumber:2
Pleaseinputthesecondnumber:3
2<3
dell@vmUbu:~/shell$bashjudgenum.sh
Pleaseinputthefirstnumber:2
Pleaseinputthesecondnumber:1
2>1
dell@vmUbu:~/shell$

知识点

1)如何判断输入的是一个整数。除了本例中的方法还可以使用expr,比如expr num + 1,如果返回值$?为0表示输入的是一个数。否则不是一个数,返回错误退出



使用Python实现

代码

#encoding:utf-8

importsys

num1=raw_input()
try:
num1=int(num1)
except:
print"Error,pleaseinputanumber."
sys.exit(2)


num2=raw_input()
try:
num2=int(num2)
except:
print"Error,pleaseinputanumber."
sys.exit(2)


if(num1>num2):
print"%d>%d"%(num1,num2)
else:
if(num1<num2):
print"%d<%d"%(num1,num2)
else:
print"%d=%d"%(num1,num2)


未完待续.......

相关文章

用的openwrt路由器,家里宽带申请了动态公网ip,为了方便把2...
#!/bin/bashcommand1&command2&wait从Shell脚本并行...
1.先查出MAMP下面集成的PHP版本cd/Applications/MAMP/bin/ph...
1、先输入locale-a,查看一下现在已安装的语言2、若不存在如...
BashPerlTclsyntaxdiff1.进制数表示Languagebinaryoctalhexa...
正常安装了k8s后,使用kubect工具后接的命令不能直接tab补全...