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:XianWeiPath=/tmp/shelltmp[-d"$Path"]||mkdir-p$Path#如果测试结果为假,就执行mkdir语句cd$Pathfor((i=0;i<10;i++))#循环执行10次donamepre=`date+%s|md5sum|tr-dc"a-z"`#生成随机的10个字母namepost='_oldboy.html'#文件名的后缀filename=${namepre}${namepost}#字符串连接touch$filenameecho"$filenamehavebeencreated."sleep1done&wait
测试
root@vmUbu:/home/dell/shell#./creat_ten_htmlfile.shadcaeeafbc_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/total8drwxr-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-8importrandomimportosdefget10char():#create10randomcharactorsseed="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"sa=[]foriinxrange(10):sa.append(random.choice(seed))salt=''.join(sa)returnsaltdefcreatefile(name):path="/tmp/shelltmp/"#checkwhetherthedirisexists,ifnotcreateitifos.path.exists(path)!=True:os.mkdir(path)pathAndName=path+namewithopen(pathAndName,"wb")asf:#createfilepassifos.path.exists(pathAndName):print"%shavebeencreated"%name#printtheresultelse:print"createfilefailed,Pleasecheckit."defmain():foriinxrange(10):#loop10timestocreate10filefilename=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;doneroot@vmUbu:/tmp/shelltmp#lsadcaeeafbc_oldgirl.htmlbeadcabbbdcbdb_oldgirl.htmledffdbddee_oldgirl.htmlfcaadeaedafbc_oldgirl.htmladddadbc_oldgirl.htmldeffebcd_oldgirl.htmlfafbbcdcfcfecef_oldgirl.htmlbcadafebdabe_oldgirl.htmlecbdeabdaedceb_oldgirl.htmlfbfdedccbcc_oldgirl.htmlroot@vmUbu:/tmp/shelltmp#
方法2:使用sed替换文件名,再用mv修改文件名
代码
#!/bin/bash#Date:2017-8-25#Author:XianWeiPath=/tmp/shelltmp[-d"$Path"]||exit0#如果测试结果为假,就执行mkdir语句cd$Pathforoldfilein`ls$Path/|grepoldboy`donewfile=`echo$oldfile|seds/oldboy/oldgirl/g`#生成新的文件名mv$oldfile$newfiledone&wait
测试
root@vmUbu:/home/dell/shell#python1_creat_ten_htmlfile.pyWKfqYfUprf_oldboy.htmlhavebeencreatedQplbhAZVZA_oldboy.htmlhavebeencreatedjmkkmepTfD_oldboy.htmlhavebeencreatedIAeFZLHzOj_oldboy.htmlhavebeencreatedDwWbMsCqtN_oldboy.htmlhavebeencreatedZgAVXNCyLQ_oldboy.htmlhavebeencreatedDBENsfnZpv_oldboy.htmlhavebeencreatedPveegnMyBo_oldboy.htmlhavebeencreatedMpReSrwXJr_oldboy.htmlhavebeencreatedSWWFrkYhdi_oldboy.htmlhavebeencreatedroot@vmUbu:/home/dell/shell#root@vmUbu:/home/dell/shell#ll/tmp/shelltmp/total8drwxr-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.htmlroot@vmUbu:/home/dell/shell#
python实现
代码
#encoding:utf-8importrandomimportosimportsysdefmain():path="/tmp/shelltmp/"ifos.path.exists(path)!=True:#checkthedirwhetherexistsprint"%snotexists,checkit."%pathsys.exit(1)forroot,dir,fileinos.walk(path):#putthedestfileintoalistpassforoldfilenameinfile:ifoldfilename.split("_")[1]=="oldboy.html":#iffilenameincludestrings"oldboy",changeitsnamenewfilename=oldfilename.split("_")[0]+"_oldgirl.html"os.rename(path+oldfilename,path+newfilename)#changenameifos.path.exists(path+newfilename):#printtheresultprint"%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.htmldxTHbQyYyZ_oldboy.htmlickDGJUVgD_oldboy.htmlLBbLaTnuRW_oldboy.htmlReFkjxYZjO_oldboy.htmltKwmVefsCP_oldboy.htmlroot@vmUbu:/home/dell/shell#python2_change_name.pyLFCkswpeJc_oldboy.htmlhavebeenchangenametoLFCkswpeJc_oldgirl.htmldxTHbQyYyZ_oldboy.htmlhavebeenchangenametodxTHbQyYyZ_oldgirl.htmlFnlInKOFDD_oldboy.htmlhavebeenchangenametoFnlInKOFDD_oldgirl.htmlRXwWPTAYTF_oldboy.htmlhavebeenchangenametoRXwWPTAYTF_oldgirl.htmlCOFoqgRped_oldboy.htmlhavebeenchangenametoCOFoqgRped_oldgirl.htmlReFkjxYZjO_oldboy.htmlhavebeenchangenametoReFkjxYZjO_oldgirl.htmlLBbLaTnuRW_oldboy.htmlhavebeenchangenametoLBbLaTnuRW_oldgirl.htmltKwmVefsCP_oldboy.htmlhavebeenchangenametotKwmVefsCP_oldgirl.htmlKraoAAesrC_oldboy.htmlhavebeenchangenametoKraoAAesrC_oldgirl.htmlickDGJUVgD_oldboy.htmlhavebeenchangenametoickDGJUVgD_oldgirl.htmlroot@vmUbu:/home/dell/shell#ls/tmp/shelltmp/COFoqgRped_oldgirl.htmlFnlInKOFDD_oldgirl.htmlKraoAAesrC_oldgirl.htmlLFCkswpeJc_oldgirl.htmlRXwWPTAYTF_oldgirl.htmldxTHbQyYyZ_oldgirl.htmlickDGJUVgD_oldgirl.htmlLBbLaTnuRW_oldgirl.htmlReFkjxYZjO_oldgirl.htmltKwmVefsCP_oldgirl.htmlroot@vmUbu:/home/dell/shell#
面试题3:批量创建用户和密码
代码
root@vmUbu:/home/dell/shell#vim3_create_user.sh#!/bin/bash#Date:2017-8-25#Author:XianWei#createtenusersinbulkfor((i=0;i<=10;i++))dousername="oldboy${i}"#cannotusesymbol''password=`tr-dc"a-zA-Z0-9"</dev/urandom|head-c8`#create8randomcharactors#echo$usernameuseradd$usernameecho$username:$password|chpasswd#changepasswd.ifos=centos,usepasswd--stdin#echo${username}""${password}echo${username}""${password}>>passwd.txt#recordtheusernameandit'spassworddone
测试
root@vmUbu:/home/dell/shell#./3_create_user.shroot@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.txtoldboy0Je28ZqTioldboy1LcA5AX3uoldboy2QF36POh3oldboy35BMoklFpoldboy418slv8fBoldboy58eIVWck3oldboy6ZuWQcqjToldboy7lSeahDHMoldboy8XvqBiFPAoldboy9VNc8fLZColdboy10zdbruc2S
python实现
代码
#encoding:utf-8'''#date:2017-8-26#Author:XianWeifromChengDu#scripteFunction:createusersandsetitspasswordinbulk'''importrandomimportosimportsysimportsubprocessimportrandomdefget_passwd(n):passwdlist=[]seed="abcdefghijkmnopqrstuvwxyz"forjinxrange(n):passwdlist.append(random.choice(seed))passwd="".join(passwdlist)returnpasswddefcreate_user(user):create_user_cmd='useradd%s'%userp=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"%userpassword=get_passwd(8)set_passwd_cmd='echo%s:%s|chpasswd'%(user,password)p2=subprocess.Popen(args=set_passwd_cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.STDOUT,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.pyuseraddoldgirl1succussfuloldgirl1setpasswordsuccussful.itspassword:qtcvheyquseraddoldgirl2succussfuloldgirl2setpasswordsuccussful.itspassword:wnaecfxuuseraddoldgirl3succussfuloldgirl3setpasswordsuccussful.itspassword:wpxwtcvvuseraddoldgirl4succussfuloldgirl4setpasswordsuccussful.itspassword:cpquxwzduseraddoldgirl5succussfuldgirl5setpasswordsuccussful.itspassword:gdtmttuguseraddoldgirl6succussfuloldgirl6setpasswordsuccussful.itspassword:eznjdjowuseraddoldgirl7succussfuloldgirl7setpasswordsuccussful.itspassword:eysxegpuuseraddoldgirl8succussfuloldgirl8setpasswordsuccussful.itspassword:yhdkrdybuseraddoldgirl9succussfuloldgirl9setpasswordsuccussful.itspassword:omytwhdhuseraddoldgirl10succussfuloldgirl10setpasswordsuccussful.itspassword:zpenokqgroot@vmUbu:/home/dell/shell#root@vmUbu:/home/dell/shell#cat/etc/passwd|grepoldgirloldgirl1: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#checktheserverwhetherisaliveippre='192.168.142.'cmd='ping-c2'for((i=0;i<=20;i++))do{$cmd$ippre$i>/dev/null2&>1if[$?-eq0]thenecho"$ippre$iisok"elseecho"$ippre$iisdown"fi}&#parallelprogressdonewait#letparentprogresswaitallchildprogress
测试
root@vmUbu:/home/dell/shell#time./4_ping_host.sh192.168.142.0isdown192.168.142.2isok192.168.142.11isdown192.168.142.20isdown192.168.142.4isdown192.168.142.12isdown192.168.142.3isdown192.168.142.9isdown192.168.142.18isdown192.168.142.5isdown192.168.142.15isdown192.168.142.13isdown192.168.142.16isdown192.168.142.17isdown192.168.142.10isdown192.168.142.14isdown192.168.142.6isdown192.168.142.19isdown192.168.142.1isdown192.168.142.7isdown192.168.142.8isdownreal0m11.229suser0m0.024ssys0m0.720s
python实现
代码
#encoding:utf-8'''#date:2017-8-26#Author:XianWeifromChengDu#scripteFunction:checkipwhetherisalivedinbulk'''importrandomimportosimportsysimportsubprocessimportrandomimportplatformimportrefromthreadingimportThreadfromQueueimportQueueimporttimedefcheck_ip(ipaddr):#函数用于检测IP地址合法性。来源:http://blog.csdn.net/jbxue123/article/details/23156011addr=ipaddr.strip().split('.')#切割IP地址为一个列表#printaddriflen(addr)!=4:#切割后列表必须有4个参数print"%s,ipaddressisillegal!"%ipaddrreturnFalseforiinrange(4):try:addr[i]=int(addr[i])#每个参数必须为数字,否则校验失败except:print"%s,ipaddressisillegal!"%ipaddrreturnFalseifaddr[i]<=255andaddr[i]>=0:#每个参数值必须在0-255之间passelse:print"%s,ipaddressisillegal!"%ipaddrreturnFalse#print"checkipaddresssuccess!"returnTruedefping_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."%ipelse:print"%sisOK."%ipif(platform.system()=="Linux"):pingResult=re.findall("DestinationHostUnreachable",res.read())if(pingResult.__len__()!=0):print"%sisdown."%ipelse:print"%sisOK."%ipdefmain():print"mainthreadingwaiting......"ip_prefix="192.168.142."#设置ip列表iplist=[]n=10foriinxrange(1,n+1):iplist.append(ip_prefix+str(i))tlist=[]foriinxrange(len(iplist)):#使用多线程pingt=Thread(target=ping_host,args=(iplist[i],))#将线程加入listtlist.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.pymainthreadingwaiting......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.mainthreadingDonereal0m3.166suser0m0.100ssys0m0.296sroot@vmUbu:/home/dell/shell#
windows平台测试
C:\Users\Administrator\PycharmProjects\shell_to_python\0826>pythonchangename.pymainthreadingwaiting......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#与一个很小的数比较thenecho-nelseecho"Error,Pleaseinputanumber"exitfi}read-p"Pleaseinputthefirstnumber:"num1judgenum$num1read-p"Pleaseinputthesecondnumber:"num2judgenum$num2letres=$num1-$num2echo$res[$res-gt0]&&echo"$num1>$num2"[$res-lt0]&&echo"$num1<$num2"[$res-eq0]&&echo"$num1=$num2"
测试
dell@vmUbu:~/shell$bashjudgenum.shPleaseinputthefirstnumber:1Pleaseinputthesecondnumber:bError,Pleaseinputanumberdell@vmUbu:~/shell$bashjudgenum.shPleaseinputthefirstnumber:aError,Pleaseinputanumberdell@vmUbu:~/shell$dell@vmUbu:~/shell$dell@vmUbu:~/shell$dell@vmUbu:~/shell$bashjudgenum.shPleaseinputthefirstnumber:2Pleaseinputthesecondnumber:22=2dell@vmUbu:~/shell$bashjudgenum.shPleaseinputthefirstnumber:2Pleaseinputthesecondnumber:32<3dell@vmUbu:~/shell$bashjudgenum.shPleaseinputthefirstnumber:2Pleaseinputthesecondnumber:12>1dell@vmUbu:~/shell$
知识点
1)如何判断输入的是一个整数。除了本例中的方法还可以使用expr,比如expr num + 1,如果返回值$?为0表示输入的是一个数。否则不是一个数,返回错误并退出
使用Python实现
代码
#encoding:utf-8importsysnum1=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)
未完待续.......
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。