Python写的系统常用命令


python写的系统常用命令,linux和windows通用,用的时候直接from util import *导入即可使用,很方便,本来是一个脚本,分成两部分发了。

  1. #!/usr/bin/python  
  2. # -*- coding: utf-8 -*-  
  3. # 通用功能类封装  
  4. import os,time,sys,string,urllib,httplib,shutil,platform,tarfile  
  5. from commands import getstatusoutput as getso  
  6. from ConfigParser import *  
  7.    
  8. def wr_log(str_cmd, status=0, result=""):  
  9.     cur_time = time.strftime("%Y-%m-%d %H:%M:%S")  
  10.     if status == 0:  
  11.         fp = open("../log/log.txt",'a+')  
  12.         fp.write("[%s]\t%s\tdone!\n" % (cur_time, str_cmd))  
  13.         fp.close()  
  14.     else:  
  15.         fp = open("../log/err_log.txt",'a+')  
  16.         fp.write("[%s]\t%s\tfailed!\n%s\n\n" % (cur_time, str_cmd, result))  
  17.         fp.close()  
  18.         sys.exit(-1)  
  19.    
  20. def wget(url, new_name=""):  
  21.     '''''  
  22.     wget封装,需提供下载地址,新文件名参数可省略。  
  23.        
  24.     例子:  
  25.     wget("http://208.asktao.com/test.txt", "/tmp/test.txt")  
  26.     ''' 
  27.     try:  
  28.         file_name = url[url.rfind("/")+1:]  
  29.         if new_name == "":  
  30.             new_name = file_name  
  31.         fp = urllib.urlopen(url)  
  32.         py_ver = sys.version[:3]  
  33.         if py_ver == "2.4":  
  34.             domain = url.split("/")[2]  
  35.             get_file = "/" + "/".join(url.split("/")[3:])  
  36.             conn = httplib.HTTPConnection(domain)  
  37.             conn.request('GET', get_file)  
  38.             fp_code = conn.getresponse().status  
  39.         else:  
  40.             fp_code = fp.getcode()  
  41.         if fp_code != 200:  
  42.             raise NameError, '%s not exist.'%file_name  
  43.         buf_len = 2048 
  44.         f = open(new_name, 'wb')  
  45.         size = 0 
  46.         while 1:  
  47.             s = fp.read(buf_len)  
  48.             if not s:  
  49.                 break 
  50.             f.write(s)  
  51.             size += len(s)  
  52.         fp.close()  
  53.         f.close()  
  54.         wr_log("wget %s"%url)  
  55.     except Exception, e:  
  56.         wr_log("wget %s"%url, 1, e)  
  57.    
  58. def sed(type, file_name, s_str="", d_str=""):  
  59.     '''''  
  60.     sed封装,根据传入的type参数执行相应操作,type可以为以下几种:  
  61.     a  在s_str行后面追加d_str,若s_str为空,则默认在文件尾部追加;  
  62.     i  在s_str行前面插入d_str,若s_str为空,则默认在文件头部插入;  
  63.     d  删除s_str所在行;  
  64.     s  将s_str替换为d_str。  
  65.        
  66.     type及file_name为必需的参数。  
  67.        
  68.     例子:  
  69.     替换字符串:sed("s", "/etc/test.txt", "abc", "123")  
  70.     ''' 
  71.     try:  
  72.         fp = open(file_name)  
  73.         cont = fp.read()  
  74.         fp.close()  
  75.         content = cont.split("\n")  
  76.         content2 = cont.split("\n")  
  77.         cnt = 0 
  78.         idx = 0 
  79.         if type == "a":  
  80.             str_cmd = "sed -i '/%s/a %s' %s" % (s_str, d_str, file_name)  
  81.             if not s_str:  
  82.                 content.append(d_str)  
  83.             else:  
  84.                 for i in content2:  
  85.                     if i.find(s_str) != -1:  
  86.                         x = idx + 1 + cnt  
  87.                         content.insert(x, d_str)  
  88.                         cnt += 1 
  89.                     idx += 1 
  90.         elif type == "i":  
  91.             str_cmd = "sed -i '/%s/i %s' %s" % (s_str, d_str, file_name)  
  92.             if not s_str:  
  93.                 content.insert(0, d_str)  
  94.             else:  
  95.                 for i in content2:  
  96.                     if i.find(s_str) != -1:  
  97.                         x = idx + cnt  
  98.                         content.insert(x, d_str)  
  99.                         cnt += 1 
  100.                     idx += 1 
  101.         elif type == "d":  
  102.             str_cmd = "sed -i '/%s/d' %s" % (s_str, file_name)  
  103.             for i in content2:  
  104.                 if i.find(s_str) != -1:  
  105.                     idx = content.remove(i)  
  106.         elif type == "s":  
  107.             str_cmd = "sed -i 's/%s/%s/g' %s" % (s_str, d_str, file_name)  
  108.             cont = string.replace(cont, s_str, d_str)  
  109.             content = cont.split("\n")  
  110.         fp = open(file_name, "w")  
  111.         fp.write("\n".join(content))  
  112.         fp.close()  
  113.         wr_log(str_cmd)  
  114.     except Exception, e:  
  115.         wr_log("modify %s" % file_name, 1, e)  
  116.    
  117. def md(dir_name):  
  118.     '''''  
  119.     mkdir封装,创建传入的目录名称。  
  120.     ''' 
  121.     try:  
  122.         if not os.path.exists(dir_name):  
  123.             os.makedirs(dir_name)  
  124.             wr_log("mkdir %s"%dir_name)  
  125.         else:  
  126.             wr_log("%s is exist."%dir_name)  
  127.     except Exception, e:  
  128.         wr_log("mkdir %s"%dir_name, 1, e)  
  129.    
  130. def mv(src, dst):  
  131.     '''''  
  132.     mv封装,移动文件或修改文件名。  
  133.     ''' 
  134.     try:  
  135.         try:  
  136.             os.rename(src, dst)  
  137.         except OSError:  
  138.             if os.path.dirname(src) == dst or os.path.dirname(src) == os.path.dirname(dst):  
  139.                 raise Exception, "Cannot move self." 
  140.             if os.path.isdir(src):  
  141.                 if os.path.abspath(dst).startswith(os.path.abspath(src)):  
  142.                     raise Exception, "Cannot move a directory to itself." 
  143.                 _copy(src, dst)  
  144.                 shutil.rmtree(src)  
  145.             else:  
  146.                 shutil.copy2(src,dst)  
  147.                 os.unlink(src)  
  148.         wr_log("mv %s %s"%(src, dst))  
  149.     except Exception, e:  
  150.         wr_log("mv %s %s"%(src, dst), 1, e)  
  151.    
  152. def cp(src, dst):  
  153.     '''''  
  154.     cp封装,复制文件或目录。  
  155.     ''' 
  156.     try:  
  157.         _copy(src, dst)  
  158.         wr_log("cp %s %s"%(src, dst))  
  159.     except Exception, e:  
  160.         wr_log("cp %s %s"%(src, dst), 1, e)  
  161.    
  162. def _copy(src, dst):  
  163.     '''''  
  164.     copy封装,供cp调用。  
  165.     ''' 
  166.     if os.path.isdir(src):  
  167.         base = os.path.basename(src)  
  168.         if os.path.exists(dst):  
  169.             dst = os.path.join(dst, base)  
  170.         if not os.path.exists(dst):  
  171.             os.makedirs(dst)  
  172.         names = os.listdir(src)  
  173.         for name in names:  
  174.             srcname = os.path.join(src, name)  
  175.             _copy(srcname, dst)  
  176.     else:  
  177.         shutil.copy2(src, dst)  
  178.    
  179. def touch(src):  
  180.     '''''  
  181.     linux适用  
  182.        
  183.     touch封装,新建空白文件。  
  184.     ''' 
  185.     str_cmd = "/bin/touch %s" % src  
  186.     status, result = getso(str_cmd)  
  187.     wr_log(str_cmd, status, result)  
  188.    
  189. def rm(src):  
  190.     '''''  
  191.     rm封装,删除文件或目录,非交互式操作,请谨慎操作。  
  192.     ''' 
  193.     try:  
  194.         if os.path.exists(src):  
  195.             if os.path.isfile(src):  
  196.                 os.remove(src)  
  197.             elif os.path.isdir(src):  
  198.                 shutil.rmtree(src)  
  199.             wr_log("rm %s" % src)  
  200.     except Exception, e:  
  201.         wr_log("rm %s" % src, 1, e)  
  202.    
  203. def chmod(num, file_name):  
  204.     '''''  
  205.     linux适用  
  206.        
  207.     chmod封装,修改文件权限。  
  208.     需要传入一个八进制数以及文件名。  
  209.        
  210.     例子:  
  211.     chmod(644, "/tmp/test.txt")  
  212.     ''' 
  213.     str_cmd = "/bin/chmod %s %s" % (num, file_name)  
  214.     status, result = getso(str_cmd)  
  215.     wr_log(str_cmd, status, result)  
  216.    
  217. def chown(user, file_name, arg=""):  
  218.     '''''  
  219.     linux适用  
  220.        
  221.     chown封装,修改文件属主属组。  
  222.        
  223.     例子:  
  224.     chown("nobody.nobody", "/tmp", "r")  
  225.     ''' 
  226.     if arg == "r":  
  227.         str_cmd = "/bin/chown -R %s %s" % (user, file_name)  
  228.     else:  
  229.         str_cmd = "/bin/chown %s %s" % (user, file_name)  
  230.     status, result = getso(str_cmd)  
  231.     wr_log(str_cmd, status, result)  
  232.    
  233. def rar(dst,src):  
  234.     '''''  
  235.     windows适用  
  236.        
  237.     winrar 压缩文件  如: rar(c:\dat.rar c:\dat)  
  238.     ''' 
  239.     try:  
  240.         if not os.path.exists(src) or not os.path.exists(os.path.dirname(dst)):  
  241.             raise Exception, "%s or %s not exist!" % (src, os.path.dirname(dst))  
  242.         os.system(r'C:\Progra~1\WinRAR\rar a %s %s' % (dst,src))  
  243.         wr_log("rar %s to %s" % (src, dst))  
  244.     except Exception,e:  
  245.         wr_log("rar %s to %s" % (src, dst), 1, e)  
  246.    
  247. def unrar(src,dst):  
  248.     '''''  
  249.     windows适用  
  250.        
  251.     unrar 解压缩rar文件 到目标路径 如:unrar(c:\dat.rar c:\)  
  252.     ''' 
  253.     try:  
  254.         if not os.path.exists(dst) or not os.path.exists(src):  
  255.             raise Exception, "%s or %s not exist!" % (src, dst)  
  256.         os.system(r'C:\Progra~1\WinRAR\rar x %s %s' % (src, dst))  
  257.         wr_log("unrar %s" % src)  
  258.     except Exception,e:  
  259.         wr_log("unrar %s" % src, 1, e)  
  260.    
  261. def tar(dst, src):  
  262.     '''''  
  263.     linux适用  
  264.        
  265.     tar封装,压缩文件。  
  266.        
  267.     例子:  
  268.     tar("/tmp/test.tgz", "/tmp/test.txt")  
  269.     ''' 
  270.     str_cmd = "/bin/tar zcf %s %s" % (dst, src)  
  271.     status, result = getso(str_cmd)  
  272.     wr_log(str_cmd, status, result)  
  273.        
  274. def untgz(tgz_file, dst="./"):  
  275.     '''''  
  276.     tar封装,解压缩文件。  
  277.        
  278.     例子:  
  279.     untgz("/tmp/test.tgz", "/tmp")  
  280.     ''' 
  281.     try:  
  282.         tarobj = tarfile.open(tgz_file)  
  283.         names = tarobj.getnames()  
  284.         for name in names:  
  285.             tarobj.extract(name,path=dst)  
  286.         tarobj.close()  
  287.         wr_log("untgz %s" % tgz_file)  
  288.     except Exception, e:  
  289.         wr_log("untgz %s" % tgz_file, 1, e)  
  290.        
  291. def kill(arg):  
  292.     '''''  
  293.     linux中,查找进程并杀死返回的pid。  
  294.     windows中,查找进程或端口并杀死返回的pid。  
  295.     ''' 
  296.     pid = get_pid(arg)  
  297.     os_type = platform.system()  
  298.     if os_type == "Linux":  
  299.         if pid:  
  300.             str_cmd = "/bin/kill -9 %s" % pid  
  301.             status, result = getso(str_cmd)  
  302.             wr_log("kill %s" % arg, status, result)  
  303.     elif os_type == "Windows":  
  304.         if pid:  
  305.             try:  
  306.                 import ctypes  
  307.                 for i in pid:  
  308.                     handle = ctypes.windll.kernel32.OpenProcess(1False, i)  
  309.                     ctypes.windll.kernel32.TerminateProcess(handle,0)  
  310.                 wr_log("kill %s" % arg)  
  311.             except Exception, e:  
  312.                 wr_log("kill %s" % arg, 1, e)  
  313.    
  314. def get_pid(arg):  
  315.     '''''  
  316.     linux中,查找进程并返回pid。  
  317.     windows中,查找进程或端口返回pid。  
  318.     ''' 
  319.     os_type = platform.system()  
  320.     if os_type == "Linux":  
  321.         str_cmd = "/bin/ps auxww | grep '%s' | grep -v grep | awk '{print $2}'" % arg  
  322.         status, result = getso(str_cmd)  
  323.         return result  
  324.     elif os_type == "Windows":  
  325.         if type(arg) == int:  
  326.             str_cmd =  "netstat -ano|find \"%s\""%arg  
  327.             try:  
  328.                 result = os.popen(str_cmd,"r").read()  
  329.                 result = result.split("\n")[0].strip()  
  330.                 if result.find("WAIT") != -1:  
  331.                     return 0 
  332.                 pid = int(result[result.rfind(" "):].strip())  
  333.                 return [pid]  
  334.             except Exception, e:  
  335.                 return 0 
  336.         else:  
  337.             import win32con,win32api,win32process  
  338.             pids = []  
  339.             for pid in win32process.EnumProcesses():  
  340.                 try:  
  341.                     hProcess = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid)  
  342.                     hProcessFirstModule = win32process.EnumProcessModules(hProcess)[0]  
  343.                     processName = os.path.splitext(os.path.split(win32process.GetModuleFileNameEx(hProcess, hProcessFirstModule))[1])[0]  
  344.                     if processName == arg:  
  345.                         pids.append(pid)  
  346.                 except Exception, e:  
  347.                     pass 
  348.             return pids  
  349.    
  350. def grpadd(grp_name):  
  351.     '''''  
  352.     linux适用  
  353.        
  354.     groupadd封装,增加组。  
  355.     ''' 
  356.     str_cmd = "/usr/sbin/groupadd %s" % grp_name  
  357.     status, result = getso(str_cmd)  
  358.     wr_log(str_cmd, status, result)  
  359.    
  360. def useradd(user_name, arg=""):  
  361.     '''''  
  362.     useradd封装,添加新用户;  
  363.     linux和windows系统分别使用不同方法;  
  364.     在linux中,arg填写新用户的gid;  
  365.     windows中,arg填写新用户的密码。  
  366.     ''' 
  367.     os_type = platform.system()  
  368.     if os_type == "Linux":  
  369.         str_cmd = "/usr/bin/id %s" % user_name  
  370.         status, result = getso(str_cmd)  
  371.         if status == 0:  
  372.             return 
  373.         if not arg:  
  374.             str_cmd = "/usr/sbin/useradd %s" % user_name  
  375.         else:  
  376.             str_cmd = "/usr/sbin/useradd -g %s %s" % (arg, user_name)  
  377.         status, result = getso(str_cmd)  
  378.         wr_log(str_cmd, status, result)  
  379.     elif os_type == "Windows":  
  380.         try:  
  381.             import win32netcon,win32net,wmi  
  382.             for use in wmi.WMI().Win32_UserAccount():  
  383.                 if use.name == user_name:  
  384.                     raise Exception, "user %s is already exists" % user_name  
  385.             udata = {}  
  386.             udata["name"] = user_name  
  387.             udata["password"] = arg  
  388.             udata["flags"] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT  
  389.             udata["priv"] = win32netcon.USER_PRIV_USER  
  390.             win32net.NetUserAdd(None1, udata)  
  391.             wr_log("add user %s" % user_name)  
  392.         except Exception,e:  
  393.             wr_log("add user %s" % user_name, 1, e)  
  394.    
  395. def userdel(user_name):  
  396.     '''''  
  397.     userdel封装,删除用户。  
  398.     ''' 
  399.     os_type = platform.system()  
  400.     if os_type == "Linux":  
  401.         str_cmd = "/usr/bin/id %s" % user_name  
  402.         status, result = getso(str_cmd)  
  403.         if status == 0:  
  404.             str_cmd = "/usr/sbin/userdel -r %s" % user_name  
  405.             status, result = getso(str_cmd)  
  406.             wr_log(str_cmd, status, result)  
  407.     elif os_type == "Windows":  
  408.         try:  
  409.             import win32net,wmi  
  410.             for use in wmi.WMI().Win32_UserAccount():  
  411.                 if use.name == user_name:  
  412.                     win32net.NetUserDel(None,user_name)  
  413.                     wr_log("del user %s" % user_name)  
  414.                     return 
  415.             wr_log("user %s not exists" % user_name)  
  416.         except Exception,e:  
  417.             wr_log("del user %s" % user_name, 1, e) 
  • 1
  • 2
  • 下一页

相关内容