您好,登錄后才能下訂單哦!
來源說明:《跟老男孩學Linux運維》Shell編程實戰
說明:對于每個腳本,用shell編程的同時,我再用python實現,達到同時熟悉兩種腳本語言的目的。由于初學python,有問題還請大家斧正。
面試題1:批量生產隨機字符文件名
用shell實現
代碼:
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 #如果測試結果為假,就執行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 "$filename have been created." sleep 1 done & wait
測試
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
總結:
考察知識點:
1)生成隨機數的方法
2)字符串連接的方法
使用Python實現
代碼
#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執行
代碼和測試:
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 #如果測試結果為假,就執行mkdir語句 cd $Path for oldfile in `ls $Path/ |grep oldboy` do newfile=`echo $oldfile | sed s/oldboy/oldgirl/g` #生成新的文件名 mv $oldfile $newfile done & wait
測試
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實現
代碼
#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()
測試
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:批量創建用戶和密碼
代碼
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
測試
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實現
代碼
#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()
測試
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:掃描網絡內存活主機
代碼
#!/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
測試
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實現
代碼
# 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): #函數用于檢測IP地址合法性。來源:http://blog.csdn.net/jbxue123/article/details/23156011 addr=ipaddr.strip().split('.') #切割IP地址為一個列表 #print addr if len(addr) != 4: #切割后列表必須有4個參數 print "%s,ip address is illegal!" %ipaddr return False for i in range(4): try: addr[i]=int(addr[i]) #每個參數必須為數字,否則校驗失敗 except: print "%s,ip address is illegal!" % ipaddr return False if addr[i]<=255 and addr[i]>=0: #每個參數值必須在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: #檢測IP合法性 sys.exit(1) platformOfSystem = platform.system() #根據平臺,設置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." #設置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: #啟動所有線程 thread.setDaemon(True) thread.start() for thread in tlist: #等待所有線程結束 thread.join() print "main threading Done" if __name__ == "__main__": main()
linux平臺測試
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平臺測試
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:比較兩個數大小
要求:輸入兩個數,比較大小并輸出結果
代碼
#!/bin/bash #Date: 2017-8-27 #Author: XianWei #作用:輸入兩個數,比較大小并輸出結果 #判斷輸入的是否為數字 function judgenum() { if [ $1 -gt -99999999 ] > /dev/null 2>&1 #與一個很小的數比較 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"
測試
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$
知識點
1)如何判斷輸入的是一個整數。除了本例中的方法還可以使用expr,比如expr num + 1,如果返回值$?為0表示輸入的是一個數。否則不是一個數,返回錯誤并退出
使用Python實現
代碼
# 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)
未完待續.......
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。