python 系統(tǒng)常用命令(二)

python封裝常用系統(tǒng)命令

python寫的系統(tǒng)常用命令,linux和windows通用倔撞,用的時(shí)候直接from util import *導(dǎo)入即可使用吕粹,很方便

#!/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 hostname(host_name):  
    '''''  
    linux適用  
       
    hostname封裝庭敦,修改主機(jī)名历涝。  
    ''' 
    str_cmd = "/bin/sed -i 's/HOSTNAME/#&/;$a HOSTNAME=%s' /etc/sysconfig/network;/bin/hostname %s" % (host_name,host_name)  
    status, result = getso(str_cmd)  
    wr_log(str_cmd, status, result)  
   
def md5sum(file_name):  
    '''''  
    md5sum封裝扭倾,獲取文件的md5值  
    ''' 
    if os.path.isfile(file_name):  
        f = open(file_name,'rb')  
        py_ver = sys.version[:3]  
        if py_ver == "2.4":  
            import md5 as hashlib  
        else:  
            import hashlib  
            md5 = hashlib.md5(f.read()).hexdigest()  
            f.close()  
            return md5  
    else:  
        return 0 
   
def md5(file_name):  
    '''''  
    linux適用  
   
    md5sum -c 封裝淀零,校驗(yàn)md5文件,返回校驗(yàn)成功或失敗狀態(tài)  
    ''' 
    str_cmd="/usr/bin/md5sum -c %s" % file_name  
    status,result=getso(str_cmd)  
    return status  
   
def grep(s_str, file_name):  
    '''''  
    grep封裝膛壹,查找文件中關(guān)鍵字驾中,有則返回所在行,否則返回空字符串模聋。  
    ''' 
    try:  
        fd = open(file_name)  
        content = fd.read()  
        result = ""  
        if content.find(s_str) != -1:  
            for line in content.split("\n"):  
                if line.find(s_str) != -1:  
                    result = result + line + "\n" 
        return result.strip()  
    except Exception, e:  
        wr_log("grep %s %s" % (s_str, file_nsme), 1, e)  
   
def rwconf(type, file_name, section, option, s_str=""):  
    '''''  
    讀取標(biāo)準(zhǔn)的ini格式配置文件肩民,type可為以下值:  
    get     獲取section下的option的值,值為字符串链方;  
    getint  獲取section下的option的值持痰,值為數(shù)字;  
    modi    修改section下的option的值祟蚀,并保存工窍;  
    del     刪除section下的option,并保存前酿。  
   
    注:option嚴(yán)格區(qū)分大小寫  
    ''' 
    try:  
        if type == "get" or type == "getint":  
            cf = ConfigParser()  
        else:  
            cf = ConfParser()  
        cf.read(file_name)  
        if type == "get":  
            return cf.get(section, option)  
        elif type == "getint":  
            return cf.getint(section, option)  
        elif type == "modi":  
            try:  
                cf.set(section, option, s_str)  
                cf.write(open(file_name, "w"))  
                wr_log("modify %s for %s" % (option, file_name))  
            except Exception, e:  
                wr_log("modify %s for %s" % (option, file_name), 1, str(e))  
        elif type == "del":  
            try:  
                cf.remove_option(section, option)  
                cf.write(open(file_name, "w"))  
                wr_log("del %s for %s" % (option, file_name))  
            except Exception, e:  
                wr_log("del %s for %s" % (option, file_name), 1, str(e))  
    except Exception, e:  
        wr_log("read %s for %s" % (option, file_name), 1, str(e))  
   
def chkconfig(type, svr_name, switch=""):  
    '''''  
    linux適用  
       
    chkconfig封裝患雏,根據(jù)傳入的type參數(shù)執(zhí)行相應(yīng)操作,type可以為以下幾種:  
    add  添加服務(wù)至啟動(dòng)項(xiàng)罢维;  
    del  從啟動(dòng)項(xiàng)刪除服務(wù)淹仑;  
    數(shù)字  指定運(yùn)行級(jí)別的服務(wù)開啟或關(guān)閉。  
       
    type及svr_name為必需的參數(shù)肺孵。  
       
    例子:  
    開啟運(yùn)行級(jí)別3的sshd服務(wù):chkconfig("3", "sshd", "on")  
    ''' 
    if type != "add" and type != "del":  
        type = "--level %s" % str(type)  
    str_cmd = "/sbin/chkconfig %s %s %s" % (type, svr_name, switch)  
    status, result = getso(str_cmd)  
    wr_log(str_cmd, status, result)  
   
def passwd(user_name,newpass):  
    '''''  
    passwd封裝匀借,修改用戶密碼  
    ''' 
    os_type = platform.system()  
    if os_type == "Linux":  
        str_cmd = "echo '%s' | passwd %s --stdin" % (newpass, user_name)  
        status, result = getso(str_cmd)  
        wr_log(str_cmd, status, result)  
    elif os_type == "Windows":  
        try:  
            if os.system('net user %s "%s" ' %(user_name,newpass)) == 0:  
                wr_log("modify passwd for %s  " % user_name)  
            elif os.system('net user %s "%s" ' %(user_name,newpass)) == 2:  
                raise Exception, "user %s isnot exists" % user_name  
        except Exception,e:  
            wr_log("modify passwd for %s " % user_name, 1, e)  
   
def echo(str, file_name):  
    '''''  
    linux適用  
   
    echo封裝,添加字符串到文件尾部  
    ''' 
    str_cmd = "/bin/echo '%s' >> %s" % (str, file_name)  
    status, result = getso(str_cmd)  
    wr_log(str_cmd, status, result)  
   
def upload(localfiles, remotepath, host="xxx", username="xxx", password="xxxx"):  
    '''''  
    上傳文件至ftp服務(wù)器平窘,默認(rèn)上傳至208FTP怀吻,如要上傳至其它FTP服務(wù)器,請(qǐng)指定host/user/pass  
   
    例:  
    upload("a.txt,b.txt", "/test/")  
    上傳a.txt初婆、b.txt文件到208的test目錄下  
    ''' 
    import base64  
    from ftplib import FTP  
    try:  
        localfiles = localfiles.split(",")  
        f =FTP(host)  
        f.login(username,password)  
        f.cwd(remotepath)  
        for localfile in localfiles:  
            fd = open(localfile,'rb')  
            f.storbinary('STOR %s' % os.path.basename(localfile),fd)  
            fd.close()  
        f.quit()  
        wr_log("upload %s" % localfiles)  
    except Exception, e:  
        wr_log("upload %s" % localfiles, 1, e)  
   
class ConfParser(RawConfigParser):  
    '''''  
    ConfigParser模塊有一個(gè)缺陷,改寫ini文件的某個(gè)section的某個(gè)option,寫入ini文件后  
    ini文件的注釋都丟掉了,并且option的大寫字母都轉(zhuǎn)換成了小寫  
    為了保存ini文件的注釋以及option的大小寫蓬坡,重寫了write、set磅叛、optionxform等方法屑咳,由rwconf函數(shù)調(diào)用  
    ''' 
    def write(self, fp):  
        """Write an .ini-format representation of the configuration state.  
   
        write ini by line no  
        """ 
           
        if self._defaults:  
            section = DEFAULTSECT  
            lineno = self._location[section]  
            self._data[lineno] = "[%s]\n" %section  
            for (key, value) in self._defaults.items():  
                if key != "__name__":  
                    wholename = section + '_' + key  #KVS  
                    lineno = self._location[wholename]  
                    self._data[lineno] = "%s = %s\n" %(key, str(value).replace('\n', '\n\t'))  
                       
        for section in self._sections:  
            lineno = self._location[section]  
            self._data[lineno] = "[%s]\n" % section  
            for (key, value) in self._sections[section].items():  
                if key != "__name__":  
                    wholename = section + '_' + key  #KVS  
                    lineno = self._location[wholename]  
                    self._data[lineno] = "%s = %s\n" %(key, str(value).replace('\n', '\n\t'))  
               
        for line in self._data:  
            fp.write("%s"%line)  
        fp.close()  
               
    def _read(self, fp, fpname):  
        """Parse a sectioned setup file.  
   
        When parsing ini file, store the line no in self._location  
        and store all lines in self._data  
        """ 
        self._location = {}  
        self._data = []  
        cursect = None      # None, or a dictionary  
        optname = None 
        lineno = 0 
        e = None            # None, or an exception  
        while True:  
            line = fp.readline()  
            self._data.append(line) #KVS  
            if not line:  
                break 
            lineno = lineno + 1 
            if line.strip() == '' or line[0] in '#;':  
                continue 
            if line.split(None, 1)[0].lower() == 'rem' and line[0] in "rR":  
                # no leading whitespace  
                continue 
            if line[0].isspace() and cursect is not None and optname:  
                value = line.strip()  
                if value:  
                    cursect[optname] = "%s\n%s" % (cursect[optname], value)  
            else:  
                mo = self.SECTCRE.match(line)  
                if mo:  
                    sectname = mo.group('header')  
                    if sectname in self._sections:  
                        cursect = self._sections[sectname]  
                    elif sectname == DEFAULTSECT:  
                        cursect = self._defaults  
                        self._location[DEFAULTSECT] = lineno -1 #KVS  
                           
                    else:  
                        cursect = {'__name__': sectname}  
                        self._location[sectname] = lineno -1 #KVS  
                        self._sections[sectname] = cursect  
   
                    optname = None 
                elif cursect is None:  
                    raise MissingSectionHeaderError(fpname, lineno, line)  
                else:  
                    mo = self.OPTCRE.match(line)  
                    if mo:  
                        optname, vi, optval = mo.group('option', 'vi', 'value')  
                        if vi in ('=', ':') and ';' in optval:  
                            pos = optval.find(';')  
                            if pos != -1 and optval[pos-1].isspace():  
                                optval = optval[:pos]  
                        optval = optval.strip()  
                        if optval == '""':  
                            optval = '' 
                        optname = self.optionxform(optname.rstrip())  
                        cursect[optname] = optval  
                           
                        if cursect == self._defaults:  
                            wholename = DEFAULTSECT + '_' + optname  #KVS  
                        else:  
                            wholename = cursect['__name__'] + '_' + optname  #KVS  
                        self._location[wholename] = lineno-1     #KVS  
                    else:  
                        if not e:  
                            e = ParsingError(fpname)  
                        e.append(lineno, repr(line))  
        if e:  
            raise e  
   
    def add_section(self, section):  
        """Create a new section in the configuration.  
   
        Raise DuplicateSectionError if a section by the specified name  
        already exists.  
        """ 
        if section in self._sections:  
            raise DuplicateSectionError(section)  
        self._sections[section] = {}  
   
        linecount = len(self._data)  
        self._data.append('\n')  
        self._data.append('%s'%section)  
        self._location[section] = linecount + 1 
   
    def set(self, section, option, value):  
        """Set an option.""" 
        if not section or section == DEFAULTSECT:  
            sectdict = self._defaults  
        else:  
            try:  
                sectdict = self._sections[section]  
            except KeyError:  
                raise NoSectionError(section)  
        option = self.optionxform(option)  
        add = False 
        if not option in sectdict:  
            add = True 
        sectdict[self.optionxform(option)] = value  
        if add:  
            lineno = self._location[section]  
            self._data.append('')  
            idx = len(self._data)  
            while idx>lineno:  
                self._data[idx-1] = self._data[idx-2]  
                idx = idx-1 
            self._data[idx+1] = '%s = %s\n'%(option,value)  
            self._location[section+'_'+option]=idx+1 
            for key in self._location:  
                if self._location[key] > lineno:  
                    self._location[key] = self._location[key] + 1 
            self._data[idx+1] = '%s = %s\n'%(option,value)  
            self._location[section+'_'+option]=idx+1 
   
    def remove_option(self, section, option):  
        """Remove an option. """ 
        if not section or section == DEFAULTSECT:  
            sectdict = self._defaults  
        else:  
            try:  
                sectdict = self._sections[section]  
            except KeyError:  
                raise NoSectionError(section)  
        option = self.optionxform(option)  
        existed = option in sectdict  
        if existed:  
            del sectdict[option]  
            wholename = section + '_' + option  
            lineno  = self._location[wholename]  
               
            del self._location[wholename]  
            for key in self._location:  
                if self._location[key] > lineno:  
                    self._location[key] = self._location[key] -1 
            del self._data[lineno]  
        return existed  
   
    def remove_section(self, section):  
        """Remove a file section.""" 
        existed = section in self._sections  
        if existed:  
            lstOpts = []  
            for option in self._sections[section]:  
                if option == '__name__':  
                    continue 
                lstOpts.append(option)  
            for option in lstOpts:  
                self.remove_option(section,option)  
   
            del self._sections[section]  
            wholename = section  
            lineno  = self._location[wholename]  
               
            del self._location[wholename]  
            for key in self._location:  
                if self._location[key] > lineno:  
                    self._location[key] = self._location[key] -1 
            del self._data[lineno]  
        return existed  
   
    def optionxform(self, optionstr):  
        ''''' 防止大小寫轉(zhuǎn)換''' 
        return optionstr 
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個(gè)濱河市弊琴,隨后出現(xiàn)的幾起案子兆龙,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 223,207評(píng)論 6 521
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件紫皇,死亡現(xiàn)場(chǎng)離奇詭異慰安,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)聪铺,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,455評(píng)論 3 400
  • 文/潘曉璐 我一進(jìn)店門化焕,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人铃剔,你說我怎么就攤上這事撒桨。” “怎么了键兜?”我有些...
    開封第一講書人閱讀 170,031評(píng)論 0 366
  • 文/不壞的土叔 我叫張陵凤类,是天一觀的道長。 經(jīng)常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 60,334評(píng)論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮楚殿,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好企锌,可當(dāng)我...
    茶點(diǎn)故事閱讀 69,322評(píng)論 6 398
  • 文/花漫 我一把揭開白布榆浓。 她就那樣靜靜地躺著于未,像睡著了一般。 火紅的嫁衣襯著肌膚如雪陡鹃。 梳的紋絲不亂的頭發(fā)上烘浦,一...
    開封第一講書人閱讀 52,895評(píng)論 1 314
  • 那天,我揣著相機(jī)與錄音萍鲸,去河邊找鬼闷叉。 笑死,一個(gè)胖子當(dāng)著我的面吹牛脊阴,可吹牛的內(nèi)容都是我干的握侧。 我是一名探鬼主播,決...
    沈念sama閱讀 41,300評(píng)論 3 424
  • 文/蒼蘭香墨 我猛地睜開眼嘿期,長吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼品擎!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起备徐,我...
    開封第一講書人閱讀 40,264評(píng)論 0 277
  • 序言:老撾萬榮一對(duì)情侶失蹤萄传,失蹤者是張志新(化名)和其女友劉穎,沒想到半個(gè)月后蜜猾,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體秀菱,經(jīng)...
    沈念sama閱讀 46,784評(píng)論 1 321
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡振诬,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,870評(píng)論 3 343
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了衍菱。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片赶么。...
    茶點(diǎn)故事閱讀 40,989評(píng)論 1 354
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖梦碗,靈堂內(nèi)的尸體忽然破棺而出禽绪,到底是詐尸還是另有隱情,我是刑警寧澤洪规,帶...
    沈念sama閱讀 36,649評(píng)論 5 351
  • 正文 年R本政府宣布印屁,位于F島的核電站,受9級(jí)特大地震影響斩例,放射性物質(zhì)發(fā)生泄漏雄人。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 42,331評(píng)論 3 336
  • 文/蒙蒙 一念赶、第九天 我趴在偏房一處隱蔽的房頂上張望础钠。 院中可真熱鬧,春花似錦叉谜、人聲如沸旗吁。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,814評(píng)論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽很钓。三九已至,卻和暖如春董栽,著一層夾襖步出監(jiān)牢的瞬間码倦,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 33,940評(píng)論 1 275
  • 我被黑心中介騙來泰國打工锭碳, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留袁稽,地道東北人。 一個(gè)月前我還...
    沈念sama閱讀 49,452評(píng)論 3 379
  • 正文 我出身青樓擒抛,卻偏偏與公主長得像推汽,于是被迫代替她去往敵國和親。 傳聞我的和親對(duì)象是個(gè)殘疾皇子歧沪,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,995評(píng)論 2 361

推薦閱讀更多精彩內(nèi)容