shell编程面试必会30题
來(lái)源說(shuō)明:《跟老男孩學(xué)Linux運(yùn)維》Shell編程實(shí)戰(zhàn)
說(shuō)明:對(duì)于每個(gè)腳本,用shell編程的同時(shí),我再用python實(shí)現(xiàn),達(dá)到同時(shí)熟悉兩種腳本語(yǔ)言的目的。由于初學(xué)python,有問(wèn)題還請(qǐng)大家斧正。
面試題1:批量生產(chǎn)隨機(jī)字符文件名
用shell實(shí)現(xiàn)
代碼:
root@vmUbu:/home/dell/shell#?vim?creat_ten_htmlfile.sh? #!/bin/bash#Date:?2017-8-25 #Author:?XianWeiPath=/tmp/shelltmp [?-d?"$Path"?]?||?mkdir?-p?$Path????????????????#如果測(cè)試結(jié)果為假,就執(zhí)行mkdir語(yǔ)句 cd?$Path for((i=0;i<10;i++))?????????????????????????????#循環(huán)執(zhí)行10次 donamepre=`date?+%s|md5sum|tr?-dc?"a-z"`??#生成隨機(jī)的10個(gè)字母namepost='_oldboy.html'?????????????????#文件名的后綴filename=${namepre}${namepost}??????????#字符串連接touch?$filenameecho?"$filename?have?been?created."sleep?1done?& wait測(cè)試
root@vmUbu:/home/dell/shell#?./creat_ten_htmlfile.sh? adcaeeafbc_oldboy.html?have?been?created. ecbdeabdaedceb_oldboy.html?have?been?created. edffdbddee_oldboy.html?have?been?created. beadcabbbdcbdb_oldboy.html?have?been?created. fcaadeaedafbc_oldboy.html?have?been?created. adddadbc_oldboy.html?have?been?created. bcadafebdabe_oldboy.html?have?been?created. deffebcd_oldboy.html?have?been?created. fafbbcdcfcfecef_oldboy.html?have?been?created. fbfdedccbcc_oldboy.html?have?been?created. root@vmUbu:/home/dell/shell#? root@vmUbu:/home/dell/shell#?ll?/tmp/shelltmp/ total?8 drwxr-xr-x??2?root?root?4096?Aug?25?07:53?./ drwxrwxrwt?15?root?root?4096?Aug?25?08:05?../ -rw-r--r--??1?root?root????0?Aug?25?07:53?adcaeeafbc_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?07:53?adddadbc_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?07:53?bcadafebdabe_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?07:53?beadcabbbdcbdb_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?07:53?deffebcd_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?07:53?ecbdeabdaedceb_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?07:53?edffdbddee_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?07:53?fafbbcdcfcfecef_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?07:53?fbfdedccbcc_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?07:53?fcaadeaedafbc_oldboy.html總結(jié):
考察知識(shí)點(diǎn):
1)生成隨機(jī)數(shù)的方法
2)字符串連接的方法
使用Python實(shí)現(xiàn)
代碼
#encoding:utf-8import?random import?osdef?get10char():????????????????????????????????????????#create?10?random?charactorsseed?=?"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"sa?=?[]for?i?in?xrange(10):sa.append(random.choice(seed))salt?=?''.join(sa)return?saltdef?createfile(name):path="/tmp/shelltmp/"?????????????????????????????????#check?whether?the?dir?is?exists,if?not?create?itif?os.path.exists(path)?!=?True:os.mkdir(path)pathAndName=path+namewith?open(pathAndName,"wb")?as?f:?????????????????????#create?filepassif?os.path.exists(pathAndName):print?"%s?have?been?created"?%name??????????????????#print?the?resultelse:print?"create?file?failed,Please?check?it."def?main():for?i?in?xrange(10):??????????????????????????????????#loop?10?times?to?create?10?filefilename=get10char()+"_oldboy.html"createfile(filename)if?__name__?==?"__main__":main()面試題2:將面試題1中的字符串oldboy全部改為oldgirl
方法一:使用awk生成所需命令,再用bash執(zhí)行
代碼和測(cè)試:
root@vmUbu:/tmp/shelltmp#?for?i?in?`ls?/tmp/shelltmp`;do?echo?$i|awk?-F?"_"?'{print?"mv?"?$0?"?"?$1"_oldgirl.html"?}'?|bash?;doneroot@vmUbu:/tmp/shelltmp#?ls adcaeeafbc_oldgirl.html????beadcabbbdcbdb_oldgirl.html??edffdbddee_oldgirl.html???????fcaadeaedafbc_oldgirl.html adddadbc_oldgirl.html??????deffebcd_oldgirl.html????????fafbbcdcfcfecef_oldgirl.html bcadafebdabe_oldgirl.html??ecbdeabdaedceb_oldgirl.html??fbfdedccbcc_oldgirl.html root@vmUbu:/tmp/shelltmp#方法2:使用sed替換文件名,再用mv修改文件名
代碼
#!/bin/bash#Date:?2017-8-25 #Author:?XianWeiPath=/tmp/shelltmp [?-d?"$Path"?]?||?exit?0????????????????#如果測(cè)試結(jié)果為假,就執(zhí)行mkdir語(yǔ)句 cd?$Pathfor?oldfile?in?`ls?$Path/?|grep?oldboy` donewfile=`echo?$oldfile?|?sed?s/oldboy/oldgirl/g`?#生成新的文件名mv?$oldfile?$newfiledone?& wait測(cè)試
root@vmUbu:/home/dell/shell#?python?1_creat_ten_htmlfile.py? WKfqYfUprf_oldboy.html?have?been?created QplbhAZVZA_oldboy.html?have?been?created jmkkmepTfD_oldboy.html?have?been?created IAeFZLHzOj_oldboy.html?have?been?created DwWbMsCqtN_oldboy.html?have?been?created ZgAVXNCyLQ_oldboy.html?have?been?created DBENsfnZpv_oldboy.html?have?been?created PveegnMyBo_oldboy.html?have?been?created MpReSrwXJr_oldboy.html?have?been?created SWWFrkYhdi_oldboy.html?have?been?created root@vmUbu:/home/dell/shell#? root@vmUbu:/home/dell/shell#?ll?/tmp/shelltmp/?????????????? total?8 drwxr-xr-x??2?root?root?4096?Aug?25?11:32?./ drwxrwxrwt?16?root?root?4096?Aug?25?11:32?../ -rw-r--r--??1?root?root????0?Aug?25?11:32?DBENsfnZpv_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?11:32?DwWbMsCqtN_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?11:32?IAeFZLHzOj_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?11:32?jmkkmepTfD_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?11:32?MpReSrwXJr_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?11:32?PveegnMyBo_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?11:32?QplbhAZVZA_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?11:32?SWWFrkYhdi_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?11:32?WKfqYfUprf_oldboy.html -rw-r--r--??1?root?root????0?Aug?25?11:32?ZgAVXNCyLQ_oldboy.html root@vmUbu:/home/dell/shell#python實(shí)現(xiàn)
代碼
#encoding:utf-8import?random import?os import?sysdef?main():path="/tmp/shelltmp/"if?os.path.exists(path)?!=True:???????????????????????????????#check?the?dir?whether?existsprint?"%s?not?exists,check?it."?%pathsys.exit(1)for?root,dir,file?in?os.walk(path):???????????????????????????#put?the?dest?file?into?a?listpassfor?oldfilename?in?file:if?oldfilename.split("_")[1]?==?"oldboy.html":??????????????#if?filename?include?strings?"oldboy",change?its?namenewfilename?=?oldfilename.split("_")[0]+"_oldgirl.html"???os.rename(path+oldfilename,path+newfilename)??????????????#change?nameif?os.path.exists(path+newfilename):??????????????????????#print?the?result?print?"%s?have?been?change?name?to?%s"?%(oldfilename,newfilename)else:print?"%s?changed?name?failed."?%(oldfilename)if?__name__?==?"__main__":main()測(cè)試
root@vmUbu:/home/dell/shell#?ls?/tmp/shelltmp/ COFoqgRped_oldboy.html??FnlInKOFDD_oldboy.html??KraoAAesrC_oldboy.html??LFCkswpeJc_oldboy.html??RXwWPTAYTF_oldboy.html dxTHbQyYyZ_oldboy.html??ickDGJUVgD_oldboy.html??LBbLaTnuRW_oldboy.html??ReFkjxYZjO_oldboy.html??tKwmVefsCP_oldboy.html root@vmUbu:/home/dell/shell#?python?2_change_name.py???????? LFCkswpeJc_oldboy.html?have?been?change?name?to?LFCkswpeJc_oldgirl.html dxTHbQyYyZ_oldboy.html?have?been?change?name?to?dxTHbQyYyZ_oldgirl.html FnlInKOFDD_oldboy.html?have?been?change?name?to?FnlInKOFDD_oldgirl.html RXwWPTAYTF_oldboy.html?have?been?change?name?to?RXwWPTAYTF_oldgirl.html COFoqgRped_oldboy.html?have?been?change?name?to?COFoqgRped_oldgirl.html ReFkjxYZjO_oldboy.html?have?been?change?name?to?ReFkjxYZjO_oldgirl.html LBbLaTnuRW_oldboy.html?have?been?change?name?to?LBbLaTnuRW_oldgirl.html tKwmVefsCP_oldboy.html?have?been?change?name?to?tKwmVefsCP_oldgirl.html KraoAAesrC_oldboy.html?have?been?change?name?to?KraoAAesrC_oldgirl.html ickDGJUVgD_oldboy.html?have?been?change?name?to?ickDGJUVgD_oldgirl.html root@vmUbu:/home/dell/shell#?ls?/tmp/shelltmp/??????? COFoqgRped_oldgirl.html??FnlInKOFDD_oldgirl.html??KraoAAesrC_oldgirl.html??LFCkswpeJc_oldgirl.html??RXwWPTAYTF_oldgirl.html dxTHbQyYyZ_oldgirl.html??ickDGJUVgD_oldgirl.html??LBbLaTnuRW_oldgirl.html??ReFkjxYZjO_oldgirl.html??tKwmVefsCP_oldgirl.html root@vmUbu:/home/dell/shell#面試題3:批量創(chuàng)建用戶(hù)和密碼
代碼
root@vmUbu:/home/dell/shell#?vim?3_create_user.sh?#!/bin/bash#Date:?2017-8-25 #Author:?XianWei #create?ten?users?in?bulkfor((i=0;i<=10;i++)) dousername="oldboy${i}"???????????????????????????#cannot?use?symbol?''password=`tr?-dc?"a-zA-Z0-9"?</dev/urandom?|head?-c?8`????????#create?8?random?charactors#echo?$username?????????useradd?$usernameecho?$username:$password?|chpasswd??????????????#change?passwd.if?os=centos,use?passwd?--stdin#echo?${username}"?"${password}?echo?${username}"?"${password}?>>?passwd.txt????#record?the?username?and?it's?password done測(cè)試
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#?cat?passwd.txt? oldboy0?Je28ZqTi oldboy1?LcA5AX3u oldboy2?QF36POh2 oldboy3?5BMoklFp oldboy4?18slv8fB oldboy5?8eIVWck3 oldboy6?ZuWQcqjT oldboy7?lSeahDHM oldboy8?XvqBiFPA oldboy9?VNc8fLZC oldboy10?zdbruc2Spython實(shí)現(xiàn)
代碼
#encoding:utf-8''' #date:?2017-8-26 #Author:?XianWei?from?ChengDu #scripte?Function:?create?users?and?set?its?password?in?bulk ''' import?random import?os import?sys import?subprocess import?randomdef?get_passwd(n):passwdlist=[]seed="abcdefghijkmnopqrstuvwxyz"for?j?in?xrange(n):passwdlist.append(random.choice(seed))passwd?=?"".join(passwdlist)return?passwddef?create_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()if?returncode?==?0:print?"useradd?%s?succussful"?%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()if?returncode_p2?==?0:print?"%s?set?password?succussful.its?password?:?%s"?%(user,password)else:print?"sorry,set?password?failed!"else:print?"useradd?failed."sys.exit(1)def?main():userlist?=?[]for?i?in?xrange(1,11):userlist.append("oldgirl"+str(i))for?user?in?userlist:create_user(user)if?__name__?==?"__main__":main()測(cè)試
root@vmUbu:/home/dell/shell#?python?3_create_user.py?????????????????????????????????????useradd?oldgirl1?succussful oldgirl1?set?password?succussful.its?password?:?qtcvheyq useradd?oldgirl2?succussful oldgirl2?set?password?succussful.its?password?:?wnaecfxu useradd?oldgirl3?succussful oldgirl3?set?password?succussful.its?password?:?wpxwtcvv useradd?oldgirl4?succussful oldgirl4?set?password?succussful.its?password?:?cpquxwzd useradd?oldgirl5?succussfuldgirl5?set?password?succussful.its?password?:?gdtmttug useradd?oldgirl6?succussful oldgirl6?set?password?succussful.its?password?:?eznjdjow useradd?oldgirl7?succussful oldgirl7?set?password?succussful.its?password?:?eysxegpu useradd?oldgirl8?succussful oldgirl8?set?password?succussful.its?password?:?yhdkrdyb useradd?oldgirl9?succussful oldgirl9?set?password?succussful.its?password?:?omytwhdh useradd?oldgirl10?succussful oldgirl10?set?password?succussful.its?password?:?zpenokqg root@vmUbu:/home/dell/shell#? root@vmUbu:/home/dell/shell#??cat?/etc/passwd?|grep?oldgirl 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:掃描網(wǎng)絡(luò)內(nèi)存活主機(jī)
代碼
測(cè)試
root@vmUbu:/home/dell/shell#?time?./4_ping_host.sh? 192.168.142.0??is?down 192.168.142.2???is?ok 192.168.142.11??is?down 192.168.142.20??is?down 192.168.142.4??is?down 192.168.142.12??is?down 192.168.142.3??is?down 192.168.142.9??is?down 192.168.142.18??is?down 192.168.142.5??is?down 192.168.142.15??is?down 192.168.142.13??is?down 192.168.142.16??is?down 192.168.142.17??is?down 192.168.142.10??is?down 192.168.142.14??is?down 192.168.142.6??is?down 192.168.142.19??is?down 192.168.142.1??is?down 192.168.142.7??is?down 192.168.142.8??is?downreal????0m11.229s user????0m0.024s sys?????0m0.720spython實(shí)現(xiàn)
代碼
#?encoding:utf-8''' #date:?2017-8-26 #Author:?XianWei?from?ChengDu #scripte?Function:?check?ip?whether?is?alived?in?bulk ''' import?random import?os import?sys import?subprocess import?random import?platform import?re from?threading?import?Thread from?Queue?import?Queue import?timedef?check_ip(ipaddr):#函數(shù)用于檢測(cè)IP地址合法性。來(lái)源:http://blog.csdn.net/jbxue123/article/details/23156011addr=ipaddr.strip().split('.')?#切割I(lǐng)P地址為一個(gè)列表#print?addrif?len(addr)?!=?4:??????????????#切割后列表必須有4個(gè)參數(shù)print?"%s,ip?address?is?illegal!"?%ipaddrreturn?Falsefor?i?in?range(4):try:addr[i]=int(addr[i])?#每個(gè)參數(shù)必須為數(shù)字,否則校驗(yàn)失敗except:print?"%s,ip?address?is?illegal!"?%?ipaddrreturn?Falseif?addr[i]<=255?and?addr[i]>=0:?#每個(gè)參數(shù)值必須在0-255之間passelse:print?"%s,ip?address?is?illegal!"?%?ipaddrreturn?False#print?"check?ip?address?success!"return?Truedef?ping_host(ip):if?check_ip(ip)?==?False:???????????????#檢測(cè)IP合法性sys.exit(1)platformOfSystem?=?platform.system()????#根據(jù)平臺(tái),設(shè)置ping命令if?(platformOfSystem?==?"Windows"):cmd?=?"ping?-n?2?%s"?%?(ip)if?(platformOfSystem?==?"Linux"):cmd?=?"ping?-c?2?%s"?%?(ip)res?=?os.popen(cmd)if?(platform.system()?==?"Windows"):if?(re.findall("Lost?=?2",?res.read()).__len__()?!=?0):print?"%s??is?down."?%?ipelse:print?"%s??is?OK."?%?ipif?(platform.system()?==?"Linux"):pingResult?=?re.findall("Destination?Host?Unreachable",?res.read())if?(pingResult.__len__()?!=?0):print?"%s??is?down."?%?ipelse:print?"%s??is?OK."?%?ipdef?main():print?"main?threading?waiting......"ip_prefix?=?"192.168.142."??????????????????????????#設(shè)置ip列表iplist?=?[]n?=?10for?i?in?xrange(1,n?+?1):iplist.append(ip_prefix?+?str(i))tlist?=?[]for?i?in?xrange(len(iplist)):???????????????????????#使用多線程pingt?=?Thread(target=ping_host,?args=(iplist[i],))?#將線程加入listtlist.append(t)for?thread?in?tlist:????????????????????????????????#啟動(dòng)所有線程thread.setDaemon(True)thread.start()for?thread?in?tlist:????????????????????????????????#等待所有線程結(jié)束thread.join()print?"main?threading?Done"if?__name__?==?"__main__":main()linux平臺(tái)測(cè)試
root@vmUbu:/home/dell/shell#?time?python?4_ping_host.py? main?threading?waiting...... 192.168.142.1??is?OK. 192.168.142.2??is?OK. 192.168.142.3??is?down. 192.168.142.6??is?down. 192.168.142.4??is?down. 192.168.142.5??is?down. 192.168.142.7??is?down.192.168.142.8??is?down. 192.168.142.9??is?down. 192.168.142.10??is?down. main?threading?Donereal????0m3.166s user????0m0.100s sys?????0m0.296s root@vmUbu:/home/dell/shell#windows平臺(tái)測(cè)試
C:\Users\Administrator\PycharmProjects\shell_to_python\0826>python?changename.pymain?threading?waiting...... 192.168.142.1??is?OK. 192.168.142.3??is?down. 192.168.142.6??is?down. 192.168.142.9??is?down.192.168.142.4??is?down. 192.168.142.7??is?down. 192.168.142.8??is?down.192.168.142.5??is?down. 192.168.142.2??is?OK.192.168.142.10??is?down.main?threading?Done面試題10:比較兩個(gè)數(shù)大小
要求:輸入兩個(gè)數(shù),比較大小并輸出結(jié)果
代碼
#!/bin/bash#Date:?2017-8-27 #Author:?XianWei #作用:輸入兩個(gè)數(shù),比較大小并輸出結(jié)果#判斷輸入的是否為數(shù)字 function?judgenum() {if?[?$1?-gt?-99999999?]?>?/dev/null?2>&1 #與一個(gè)很小的數(shù)比較thenecho?-nelseecho?"Error,Please?input?a?number"exitfi }read?-p?"Please?input?the?first?number:"?num1 judgenum?$num1 read?-p?"Please?input?the?second?number:"?num2 judgenum?$num2let?res=$num1-$num2 echo?$res[?$res?-gt?0?]?&&?echo?"$num1?>?$num2" [?$res?-lt?0?]?&&?echo?"$num1?<?$num2" [?$res?-eq?0?]?&&?echo?"$num1?=?$num2"測(cè)試
dell@vmUbu:~/shell$?bash?judgenum.sh? Please?input?the?first?number:1 Please?input?the?second?number:b Error,Please?input?a?number dell@vmUbu:~/shell$?bash?judgenum.sh?? Please?input?the?first?number:a Error,Please?input?a?number dell@vmUbu:~/shell$? dell@vmUbu:~/shell$? dell@vmUbu:~/shell$? dell@vmUbu:~/shell$?bash?judgenum.sh?? Please?input?the?first?number:2 Please?input?the?second?number:2 2?=?2 dell@vmUbu:~/shell$?bash?judgenum.sh? Please?input?the?first?number:2 Please?input?the?second?number:3 2?<?3 dell@vmUbu:~/shell$?bash?judgenum.sh? Please?input?the?first?number:2 Please?input?the?second?number:1 2?>?1 dell@vmUbu:~/shell$知識(shí)點(diǎn)
????1)如何判斷輸入的是一個(gè)整數(shù)。除了本例中的方法還可以使用expr,比如expr num + 1,如果返回值$?為0表示輸入的是一個(gè)數(shù)。否則不是一個(gè)數(shù),返回錯(cuò)誤并退出
使用Python實(shí)現(xiàn)
代碼
#?encoding:utf-8import?sysnum1?=?raw_input() try:num1?=?int(num1) except:print?"Error?,please?input?a?number."sys.exit(2)num2?=?raw_input() try:num2?=?int(num2) except:print?"Error?,please?input?a?number."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)未完待續(xù).......
轉(zhuǎn)載于:https://blog.51cto.com/237085/1959480
總結(jié)
以上是生活随笔為你收集整理的shell编程面试必会30题的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: CSS美化上传按钮、checkbox和r
- 下一篇: 虚拟机里安装Linux系统出现乱码