来源说明:《跟老男孩学Linux运维》Shell编程实战
创新互联公司主要从事成都做网站、成都网站建设、网页设计、企业做网站、公司建网站等业务。立足成都服务贵阳,十多年网站建设经验,价格优惠、服务专业,欢迎来电咨询建站服务:028-86922220说明:对于每个脚本,用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" > 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未完待续.......
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
分享名称:shell编程面试必会30题-创新互联
文章位置:http://chengdu.cdxwcx.cn/article/pdhdo.html