來源說明:《跟老男孩學(xué)Linux運(yùn)維》Shell編程實(shí)戰(zhàn)
說明:對(duì)于每個(gè)腳本,用shell編程的同時(shí),我再用python實(shí)現(xiàn),達(dá)到同時(shí)熟悉兩種腳本語言的目的。由于初學(xué)python,有問題還請(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: XianWei Path=/tmp/shelltmp [ -d "$Path" ] || mkdir -p $Path #如果測(cè)試結(jié)果為假,就執(zhí)行mkdir語句 cd $Path for((i=0;i<10;i++)) #循環(huán)執(zhí)行10次 do namepre=`date +%s|md5sum|tr -dc "a-z"` #生成隨機(jī)的10個(gè)字母 namepost='_oldboy.html' #文件名的后綴 filename=${namepre}${namepost} #字符串連接 touch $filename echo "$filename have been created." sleep 1 done & 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-8 import random import os def get10char(): #create 10 random charactors seed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" sa = [] for i in xrange(10): sa.append(random.choice(seed)) salt = ''.join(sa) return salt def createfile(name): path="/tmp/shelltmp/" #check whether the dir is exists,if not create it if os.path.exists(path) != True: os.mkdir(path) pathAndName=path+name with open(pathAndName,"wb") as f: #create file pass if os.path.exists(pathAndName): print "%s have been created" %name #print the result else: print "create file failed,Please check it." def main(): for i in xrange(10): #loop 10 times to create 10 file filename=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 ;done root@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: XianWei Path=/tmp/shelltmp [ -d "$Path" ] || exit 0 #如果測(cè)試結(jié)果為假,就執(zhí)行mkdir語句 cd $Path for oldfile in `ls $Path/ |grep oldboy` do newfile=`echo $oldfile | sed s/oldboy/oldgirl/g` #生成新的文件名 mv $oldfile $newfile done & 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-8 import random import os import sys def main(): path="/tmp/shelltmp/" if os.path.exists(path) !=True: #check the dir whether exists print "%s not exists,check it." %path sys.exit(1) for root,dir,file in os.walk(path): #put the dest file into a list pass for oldfilename in file: if oldfilename.split("_")[1] == "oldboy.html": #if filename include strings "oldboy",change its name newfilename = oldfilename.split("_")[0]+"_oldgirl.html" os.rename(path+oldfilename,path+newfilename) #change name if 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)建用戶和密碼
代碼
root@vmUbu:/home/dell/shell# vim 3_create_user.sh #!/bin/bash #Date: 2017-8-25 #Author: XianWei #create ten users in bulk for((i=0;i<=10;i++)) do username="oldboy${i}" #cannot use symbol '' password=`tr -dc "a-zA-Z0-9" </dev/urandom |head -c 8` #create 8 random charactors #echo $username useradd $username echo $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 QF36POh3 oldboy3 5BMoklFp oldboy4 18slv8fB oldboy5 8eIVWck3 oldboy6 ZuWQcqjT oldboy7 lSeahDHM oldboy8 XvqBiFPA oldboy9 VNc8fLZC oldboy10 zdbruc2S
python實(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 random def get_passwd(n): passwdlist=[] seed="abcdefghijkmnopqrstuvwxyz" for j in xrange(n): passwdlist.append(random.choice(seed)) passwd = "".join(passwdlist) return passwd def create_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() if returncode == 0: print "useradd %s succussful" %user password=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 succussful dgirl5 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ī)
代碼
#!/bin/bash #Date: 2017-8-26 #Author: XianWei #check the server whether is alive ippre='192.168.142.' cmd='ping -c2 ' for((i=0;i<=20;i++)) do { $cmd $ippre$i > /dev/null 2&>1 if [ $? -eq 0 ] then echo "$ippre$i is ok" else echo "$ippre$i is down" fi }& #parallel progress done wait #let parent progress wait all child progress
測(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 down real 0m11.229s user 0m0.024s sys 0m0.720s
python實(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 time def check_ip(ipaddr): #函數(shù)用于檢測(cè)IP地址合法性。來源:http://blog.csdn.net/jbxue123/article/details/23156011 addr=ipaddr.strip().split('.') #切割I(lǐng)P地址為一個(gè)列表 #print addr if len(addr) != 4: #切割后列表必須有4個(gè)參數(shù) print "%s,ip address is illegal!" %ipaddr return False for i in range(4): try: addr[i]=int(addr[i]) #每個(gè)參數(shù)必須為數(shù)字,否則校驗(yàn)失敗 except: print "%s,ip address is illegal!" % ipaddr return False if addr[i]<=255 and addr[i]>=0: #每個(gè)參數(shù)值必須在0-255之間 pass else: print "%s,ip address is illegal!" % ipaddr return False #print "check ip address success!" return True def 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." % ip else: print "%s is OK." % ip if (platform.system() == "Linux"): pingResult = re.findall("Destination Host Unreachable", res.read()) if (pingResult.__len__() != 0): print "%s is down." % ip else: print "%s is OK." % ip def main(): print "main threading waiting......" ip_prefix = "192.168.142." #設(shè)置ip列表 iplist = [] n = 10 for i in xrange(1,n + 1): iplist.append(ip_prefix + str(i)) tlist = [] for i in xrange(len(iplist)): #使用多線程ping t = Thread(target=ping_host, args=(iplist[i],)) #將線程加入list tlist.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 Done real 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.py main 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ù)比較 then echo -n else echo "Error,Please input a number" exit fi } read -p "Please input the first number:" num1 judgenum $num1 read -p "Please input the second number:" num2 judgenum $num2 let 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-8 import sys num1 = 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ù).......
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性價(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專為企業(yè)上云打造定制,能夠滿足用戶豐富、多元化的應(yīng)用場(chǎng)景需求。
本文標(biāo)題:shell編程面試必會(huì)30題-創(chuàng)新互聯(lián)
分享URL:http://www.rwnh.cn/article10/pdhdo.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站改版、微信公眾號(hào)、關(guān)鍵詞優(yōu)化、網(wǎng)站內(nèi)鏈、做網(wǎng)站、營(yíng)銷型網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容