python 系統常用命令(一)

python寫的系統常用命令

linux和windows通用,用的時候直接from util import *導入即可使用,很方便。

#!/usr/bin/python  
# -*- coding: utf-8 -*-  
# 通用功能類封裝  
import os,time,sys,string,urllib,httplib,shutil,platform,tarfile  
from commands import getstatusoutput as getso  
from ConfigParser import *  
   
def wr_log(str_cmd, status=0, result=""):  
    cur_time = time.strftime("%Y-%m-%d %H:%M:%S")  
    if status == 0:  
        fp = open("../log/log.txt",'a+')  
        fp.write("[%s]\t%s\tdone!\n" % (cur_time, str_cmd))  
        fp.close()  
    else:  
        fp = open("../log/err_log.txt",'a+')  
        fp.write("[%s]\t%s\tfailed!\n%s\n\n" % (cur_time, str_cmd, result))  
        fp.close()  
        sys.exit(-1)  
   
def wget(url, new_name=""):  
    '''''  
    wget封裝,需提供下載地址,新文件名參數可省略。  
       
    例子:  
    wget("http://192.168.1.100/test.txt", "/tmp/test.txt")  
    ''' 
    try:  
        file_name = url[url.rfind("/")+1:]  
        if new_name == "":  
            new_name = file_name  
        fp = urllib.urlopen(url)  
        py_ver = sys.version[:3]  
        if py_ver == "2.4":  
            domain = url.split("/")[2]  
            get_file = "/" + "/".join(url.split("/")[3:])  
            conn = httplib.HTTPConnection(domain)  
            conn.request('GET', get_file)  
            fp_code = conn.getresponse().status  
        else:  
            fp_code = fp.getcode()  
        if fp_code != 200:  
            raise NameError, '%s not exist.'%file_name  
        buf_len = 2048 
        f = open(new_name, 'wb')  
        size = 0 
        while 1:  
            s = fp.read(buf_len)  
            if not s:  
                break 
            f.write(s)  
            size += len(s)  
        fp.close()  
        f.close()  
        wr_log("wget %s"%url)  
    except Exception, e:  
        wr_log("wget %s"%url, 1, e)  
   
def sed(type, file_name, s_str="", d_str=""):  
    '''''  
    sed封裝,根據傳入的type參數執行相應操作,type可以為以下幾種:  
    a  在s_str行后面追加d_str,若s_str為空,則默認在文件尾部追加;  
    i  在s_str行前面插入d_str,若s_str為空,則默認在文件頭部插入;  
    d  刪除s_str所在行;  
    s  將s_str替換為d_str。  
       
    type及file_name為必需的參數。  
       
    例子:  
    替換字符串:sed("s", "/etc/test.txt", "abc", "123")  
    ''' 
    try:  
        fp = open(file_name)  
        cont = fp.read()  
        fp.close()  
        content = cont.split("\n")  
        content2 = cont.split("\n")  
        cnt = 0 
        idx = 0 
        if type == "a":  
            str_cmd = "sed -i '/%s/a %s' %s" % (s_str, d_str, file_name)  
            if not s_str:  
                content.append(d_str)  
            else:  
                for i in content2:  
                    if i.find(s_str) != -1:  
                        x = idx + 1 + cnt  
                        content.insert(x, d_str)  
                        cnt += 1 
                    idx += 1 
        elif type == "i":  
            str_cmd = "sed -i '/%s/i %s' %s" % (s_str, d_str, file_name)  
            if not s_str:  
                content.insert(0, d_str)  
            else:  
                for i in content2:  
                    if i.find(s_str) != -1:  
                        x = idx + cnt  
                        content.insert(x, d_str)  
                        cnt += 1 
                    idx += 1 
        elif type == "d":  
            str_cmd = "sed -i '/%s/d' %s" % (s_str, file_name)  
            for i in content2:  
                if i.find(s_str) != -1:  
                    idx = content.remove(i)  
        elif type == "s":  
            str_cmd = "sed -i 's/%s/%s/g' %s" % (s_str, d_str, file_name)  
            cont = string.replace(cont, s_str, d_str)  
            content = cont.split("\n")  
        fp = open(file_name, "w")  
        fp.write("\n".join(content))  
        fp.close()  
        wr_log(str_cmd)  
    except Exception, e:  
        wr_log("modify %s" % file_name, 1, e)  
   
def md(dir_name):  
    '''''  
    mkdir封裝,創建傳入的目錄名稱。  
    ''' 
    try:  
        if not os.path.exists(dir_name):  
            os.makedirs(dir_name)  
            wr_log("mkdir %s"%dir_name)  
        else:  
            wr_log("%s is exist."%dir_name)  
    except Exception, e:  
        wr_log("mkdir %s"%dir_name, 1, e)  
   
def mv(src, dst):  
    '''''  
    mv封裝,移動文件或修改文件名。  
    ''' 
    try:  
        try:  
            os.rename(src, dst)  
        except OSError:  
            if os.path.dirname(src) == dst or os.path.dirname(src) == os.path.dirname(dst):  
                raise Exception, "Cannot move self." 
            if os.path.isdir(src):  
                if os.path.abspath(dst).startswith(os.path.abspath(src)):  
                    raise Exception, "Cannot move a directory to itself." 
                _copy(src, dst)  
                shutil.rmtree(src)  
            else:  
                shutil.copy2(src,dst)  
                os.unlink(src)  
        wr_log("mv %s %s"%(src, dst))  
    except Exception, e:  
        wr_log("mv %s %s"%(src, dst), 1, e)  
   
def cp(src, dst):  
    '''''  
    cp封裝,復制文件或目錄。  
    ''' 
    try:  
        _copy(src, dst)  
        wr_log("cp %s %s"%(src, dst))  
    except Exception, e:  
        wr_log("cp %s %s"%(src, dst), 1, e)  
   
def _copy(src, dst):  
    '''''  
    copy封裝,供cp調用。  
    ''' 
    if os.path.isdir(src):  
        base = os.path.basename(src)  
        if os.path.exists(dst):  
            dst = os.path.join(dst, base)  
        if not os.path.exists(dst):  
            os.makedirs(dst)  
        names = os.listdir(src)  
        for name in names:  
            srcname = os.path.join(src, name)  
            _copy(srcname, dst)  
    else:  
        shutil.copy2(src, dst)  
   
def touch(src):  
    '''''  
    linux適用  
       
    touch封裝,新建空白文件。  
    ''' 
    str_cmd = "/bin/touch %s" % src  
    status, result = getso(str_cmd)  
    wr_log(str_cmd, status, result)  
   
def rm(src):  
    '''''  
    rm封裝,刪除文件或目錄,非交互式操作,請謹慎操作。  
    ''' 
    try:  
        if os.path.exists(src):  
            if os.path.isfile(src):  
                os.remove(src)  
            elif os.path.isdir(src):  
                shutil.rmtree(src)  
            wr_log("rm %s" % src)  
    except Exception, e:  
        wr_log("rm %s" % src, 1, e)  
   
def chmod(num, file_name):  
    '''''  
    linux適用  
       
    chmod封裝,修改文件權限。  
    需要傳入一個八進制數以及文件名。  
       
    例子:  
    chmod(644, "/tmp/test.txt")  
    ''' 
    str_cmd = "/bin/chmod %s %s" % (num, file_name)  
    status, result = getso(str_cmd)  
    wr_log(str_cmd, status, result)  
   
def chown(user, file_name, arg=""):  
    '''''  
    linux適用  
       
    chown封裝,修改文件屬主屬組。  
       
    例子:  
    chown("nobody.nobody", "/tmp", "r")  
    ''' 
    if arg == "r":  
        str_cmd = "/bin/chown -R %s %s" % (user, file_name)  
    else:  
        str_cmd = "/bin/chown %s %s" % (user, file_name)  
    status, result = getso(str_cmd)  
    wr_log(str_cmd, status, result)  
   
def rar(dst,src):  
    '''''  
    windows適用  
       
    winrar 壓縮文件  如: rar(c:\dat.rar c:\dat)  
    ''' 
    try:  
        if not os.path.exists(src) or not os.path.exists(os.path.dirname(dst)):  
            raise Exception, "%s or %s not exist!" % (src, os.path.dirname(dst))  
        os.system(r'C:\Progra~1\WinRAR\rar a %s %s' % (dst,src))  
        wr_log("rar %s to %s" % (src, dst))  
    except Exception,e:  
        wr_log("rar %s to %s" % (src, dst), 1, e)  
   
def unrar(src,dst):  
    '''''  
    windows適用  
       
    unrar 解壓縮rar文件 到目標路徑 如:unrar(c:\dat.rar c:\)  
    ''' 
    try:  
        if not os.path.exists(dst) or not os.path.exists(src):  
            raise Exception, "%s or %s not exist!" % (src, dst)  
        os.system(r'C:\Progra~1\WinRAR\rar x %s %s' % (src, dst))  
        wr_log("unrar %s" % src)  
    except Exception,e:  
        wr_log("unrar %s" % src, 1, e)  
   
def tar(dst, src):  
    '''''  
    linux適用  
       
    tar封裝,壓縮文件。  
       
    例子:  
    tar("/tmp/test.tgz", "/tmp/test.txt")  
    ''' 
    str_cmd = "/bin/tar zcf %s %s" % (dst, src)  
    status, result = getso(str_cmd)  
    wr_log(str_cmd, status, result)  
       
def untgz(tgz_file, dst="./"):  
    '''''  
    tar封裝,解壓縮文件。  
       
    例子:  
    untgz("/tmp/test.tgz", "/tmp")  
    ''' 
    try:  
        tarobj = tarfile.open(tgz_file)  
        names = tarobj.getnames()  
        for name in names:  
            tarobj.extract(name,path=dst)  
        tarobj.close()  
        wr_log("untgz %s" % tgz_file)  
    except Exception, e:  
        wr_log("untgz %s" % tgz_file, 1, e)  
       
def kill(arg):  
    '''''  
    linux中,查找進程并殺死返回的pid。  
    windows中,查找進程或端口并殺死返回的pid。  
    ''' 
    pid = get_pid(arg)  
    os_type = platform.system()  
    if os_type == "Linux":  
        if pid:  
            str_cmd = "/bin/kill -9 %s" % pid  
            status, result = getso(str_cmd)  
            wr_log("kill %s" % arg, status, result)  
    elif os_type == "Windows":  
        if pid:  
            try:  
                import ctypes  
                for i in pid:  
                    handle = ctypes.windll.kernel32.OpenProcess(1, False, i)  
                    ctypes.windll.kernel32.TerminateProcess(handle,0)  
                wr_log("kill %s" % arg)  
            except Exception, e:  
                wr_log("kill %s" % arg, 1, e)  
   
def get_pid(arg):  
    '''''  
    linux中,查找進程并返回pid。  
    windows中,查找進程或端口返回pid。  
    ''' 
    os_type = platform.system()  
    if os_type == "Linux":  
        str_cmd = "/bin/ps auxww | grep '%s' | grep -v grep | awk '{print $2}'" % arg  
        status, result = getso(str_cmd)  
        return result  
    elif os_type == "Windows":  
        if type(arg) == int:  
            str_cmd =  "netstat -ano|find \"%s\""%arg  
            try:  
                result = os.popen(str_cmd,"r").read()  
                result = result.split("\n")[0].strip()  
                if result.find("WAIT") != -1:  
                    return 0 
                pid = int(result[result.rfind(" "):].strip())  
                return [pid]  
            except Exception, e:  
                return 0 
        else:  
            import win32con,win32api,win32process  
            pids = []  
            for pid in win32process.EnumProcesses():  
                try:  
                    hProcess = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid)  
                    hProcessFirstModule = win32process.EnumProcessModules(hProcess)[0]  
                    processName = os.path.splitext(os.path.split(win32process.GetModuleFileNameEx(hProcess, hProcessFirstModule))[1])[0]  
                    if processName == arg:  
                        pids.append(pid)  
                except Exception, e:  
                    pass 
            return pids  
   
def grpadd(grp_name):  
    '''''  
    linux適用  
       
    groupadd封裝,增加組。  
    ''' 
    str_cmd = "/usr/sbin/groupadd %s" % grp_name  
    status, result = getso(str_cmd)  
    wr_log(str_cmd, status, result)  
   
def useradd(user_name, arg=""):  
    '''''  
    useradd封裝,添加新用戶;  
    linux和windows系統分別使用不同方法;  
    在linux中,arg填寫新用戶的gid;  
    windows中,arg填寫新用戶的密碼。  
    ''' 
    os_type = platform.system()  
    if os_type == "Linux":  
        str_cmd = "/usr/bin/id %s" % user_name  
        status, result = getso(str_cmd)  
        if status == 0:  
            return 
        if not arg:  
            str_cmd = "/usr/sbin/useradd %s" % user_name  
        else:  
            str_cmd = "/usr/sbin/useradd -g %s %s" % (arg, user_name)  
        status, result = getso(str_cmd)  
        wr_log(str_cmd, status, result)  
    elif os_type == "Windows":  
        try:  
            import win32netcon,win32net,wmi  
            for use in wmi.WMI().Win32_UserAccount():  
                if use.name == user_name:  
                    raise Exception, "user %s is already exists" % user_name  
            udata = {}  
            udata["name"] = user_name  
            udata["password"] = arg  
            udata["flags"] = win32netcon.UF_NORMAL_ACCOUNT | win32netcon.UF_SCRIPT  
            udata["priv"] = win32netcon.USER_PRIV_USER  
            win32net.NetUserAdd(None, 1, udata)  
            wr_log("add user %s" % user_name)  
        except Exception,e:  
            wr_log("add user %s" % user_name, 1, e)  
   
def userdel(user_name):  
    '''''  
    userdel封裝,刪除用戶。  
    ''' 
    os_type = platform.system()  
    if os_type == "Linux":  
        str_cmd = "/usr/bin/id %s" % user_name  
        status, result = getso(str_cmd)  
        if status == 0:  
            str_cmd = "/usr/sbin/userdel -r %s" % user_name  
            status, result = getso(str_cmd)  
            wr_log(str_cmd, status, result)  
    elif os_type == "Windows":  
        try:  
            import win32net,wmi  
            for use in wmi.WMI().Win32_UserAccount():  
                if use.name == user_name:  
                    win32net.NetUserDel(None,user_name)  
                    wr_log("del user %s" % user_name)  
                    return 
            wr_log("user %s not exists" % user_name)  
        except Exception,e:  
            wr_log("del user %s" % user_name, 1, e) 
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Spring Cloud為開發人員提供了快速構建分布式系統中一些常見模式的工具(例如配置管理,服務發現,斷路器,智...
    卡卡羅2017閱讀 134,993評論 19 139
  • # Python 資源大全中文版 我想很多程序員應該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,595評論 6 427
  • 前言 Python的創始人為Guido van Rossum。1989年圣誕節期間,在阿姆斯特丹,Guido為了打...
    依依玖玥閱讀 3,611評論 6 37
  • 1. Java基礎部分 基礎部分的順序:基本語法,類相關的語法,內部類的語法,繼承相關的語法,異常的語法,線程的語...
    子非魚_t_閱讀 31,779評論 18 399
  • 我從最初的不喜歡吃螺螄粉到現在一天兩碗 從不愛運動到堅持健身 從對瑜伽有偏見到也開始練習瑜伽 從不喜歡火龍果 木瓜...
    櫻桃城城閱讀 357評論 0 0