python 系统常用命令(二)

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 hostname(host_name):  
    '''''  
    linux适用  
       
    hostname封装,修改主机名。  
    ''' 
    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 封装,校验md5文件,返回校验成功或失败状态  
    ''' 
    str_cmd="/usr/bin/md5sum -c %s" % file_name  
    status,result=getso(str_cmd)  
    return status  
   
def grep(s_str, file_name):  
    '''''  
    grep封装,查找文件中关键字,有则返回所在行,否则返回空字符串。  
    ''' 
    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=""):  
    '''''  
    读取标准的ini格式配置文件,type可为以下值:  
    get     获取section下的option的值,值为字符串;  
    getint  获取section下的option的值,值为数字;  
    modi    修改section下的option的值,并保存;  
    del     删除section下的option,并保存。  
   
    注:option严格区分大小写  
    ''' 
    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封装,根据传入的type参数执行相应操作,type可以为以下几种:  
    add  添加服务至启动项;  
    del  从启动项删除服务;  
    数字  指定运行级别的服务开启或关闭。  
       
    type及svr_name为必需的参数。  
       
    例子:  
    开启运行级别3的sshd服务: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服务器,默认上传至208FTP,如要上传至其它FTP服务器,请指定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模块有一个缺陷,改写ini文件的某个section的某个option,写入ini文件后  
    ini文件的注释都丢掉了,并且option的大写字母都转换成了小写  
    为了保存ini文件的注释以及option的大小写,重写了write、set、optionxform等方法,由rwconf函数调用  
    ''' 
    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):  
        ''''' 防止大小写转换''' 
        return optionstr 
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,445评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 85,889评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,047评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,760评论 1 276
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,745评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,638评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,011评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,669评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,923评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,655评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,740评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,406评论 4 320
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,995评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,961评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,197评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,023评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,483评论 2 342

推荐阅读更多精彩内容