Loading [MathJax]/jax/output/CommonHTML/config.js
首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >专栏 >python写的系统常用命令(二)

python写的系统常用命令(二)

作者头像
py3study
发布于 2020-01-09 15:56:05
发布于 2020-01-09 15:56:05
63100
代码可运行
举报
文章被收录于专栏:python3python3
运行总次数:0
代码可运行

python写的系统常用命令,linux和windows通用,用的时候直接from util import *导入即可使用,很方便

代码语言:javascript
代码运行次数:0
运行
AI代码解释
复制
#!/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 
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019/09/12 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
暂无评论
推荐阅读
编辑精选文章
换一批
python写的系统常用命令(一)
      python写的系统常用命令,linux和windows通用,用的时候直接from util import *导入即可使用,很方便,本来是一个脚本,但是博文有字数限制,只能分成两部分发了,第二部分连接:http://wangwei007.blog.51cto.com/68019/960000 。
py3study
2020/01/06
3920
python常用模块二
我们的登录密码在数据库中不能存明文,当别人拿到数据库,看到账号密码是很恐怖的事情。所以我们就需要hashilib模块来加密。前几年csdn的数据库外泄,而且存的是明文,就很麻烦,所幸并不没有涉及大量¥。
不断折腾
2019/09/23
4180
Python之几种常用模块
模块 注意事项: 所有的模块导入都应该尽量往上写 内置模块 扩展模块 自定义模块 模块不会重复被导入 : sys.moudles 从哪儿导入模块 : sys.path import import 模块名 模块名.变量名 和本文件中的变量名完全不冲突 import 模块名 as 重命名的模块名 : 提高代码的兼容性 import 模块1,模块2 from import from 模块名 import 变量名 直接使用 变量名 就可以完成操作 如果本文件中有相同
新人小试
2018/04/12
1.4K0
Python之几种常用模块
写简历,从来没有这么简单
今天就是2024年高考了,再过一个月,新一季大学毕业生也要去社会“接受毒打”。现在大环境找工作也面对僧对粥少,在这个严峻的时代,学会这一招可以让你“快”人一步,打造你的个人简历。我来讲一讲怎么用Python工具来快速产生简历。
mariolu
2024/06/06
1450
python 运维常用脚本
path = "D:/UASM64/include/" dirs = os.listdir(path) temp=[];
用户5760343
2019/07/31
3.7K0
IDL常用命令总结
创建索引数组:findgen(num),dindgen(num) 创建一个特定纬度的数组并赋值:replicate(2.0,4,2),创建4列2行值为2.0的数组
Twcat_tree
2022/12/05
5670
mht文件图片解析工具(兼容Chrome/Blink)
之前写过一个mht文件的解析工具,不过当时解析的文件都是ie生成的。没有测试过chrome解析的文件。今天在github上看到一个反馈:https://github.com/obaby/mht-image-extractor/issues/1 qq浏览器保存的文件无法提取,chrome保存的文件会直接崩溃。下载附件的文件解析后发现,这两个文件的文件格式与ie的文件格式并不一致,文件头改成了如下的内容:
obaby
2023/02/23
1.1K0
mht文件图片解析工具(兼容Chrome/Blink)
Linux常用命令(合集)
其中-d表示显示变化的差异内容,-n指观察间隔,后面跟数字,-n1表示1秒观察一次。
Jensen_97
2023/07/20
2610
Python常用模块
json.dump和json.load不常用,主要是针对文件操作进行序列化和反序列化
星陨1357
2023/03/14
6440
Python常用模块
跨平台PHP调试器设计及使用方法——协议解析
        在《跨平台PHP调试器设计及使用方法——探索和设计》一文中,我介绍了将使用pydbgp作为和Xdebug的通信库,并让pydbgp以(孙)子进程的方式存在。《跨平台PHP调试器设计及使用方法——通信》解决了和pydbgp通信的问题,本文将讲解和pydbgp通信协议的问题。(转载请指明出于breaksoftware的csdn博客)
方亮
2019/01/16
7770
python 日志记录
#!/bin/env python #--*-- coding=utf8 --*-- # # Author: ablozhou # E-mail: ablozhou@gmail.com # # Copyright 2010 ablozhou # # Distributed under the terms of the GPL (GNU Public License) # # hzdq is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA # # 2010.3.14 写文件,log级别常数定义 import datetime import sys import traceback import codecs import types #log编码全部按utf8处理 loglevels = {'stdout':['info','debug','warn','error','fatal'], 'file':['info','debug','warn','error','fatal'] } logfile = 'logs.txt' class log4py: def __init__(self,modulename='gloabal', loglevel=loglevels, filename='log4py.txt'): self.filename = filename #self.flag = set(loglevel['stdout']+loglevel['file']) self.loglevel = loglevel self.modulename = modulename self.fcname = None class function(): def __init__(self,fcname,parent): parent.debug('enter ',fcname) self.fcname = fcname self.parent = parent def __del__(self): self.parent.debug('exit ',self.fcname) def dbgfc(self,fcname): '''set debug function name''' f = None if 'debug' in self.flag: f = self.function(fcname,self) return f def _gettime(self): return datetime.datetime.now().isoformat() def outstd(self,*fmt): s = self.fmtstr(*fmt) print s def outfile
py3study
2020/01/03
1.1K0
pythonpcap原生python读取
本文代码都由python编写,无需安装第三方拓展库,代码更新:https://github.com/mengdj/python
py3study
2020/01/03
1.6K0
pythonpcap原生python读取
Python常用模块集锦
Python常用模块集锦 常用模块主要分为以下几类(缺失的后续再补充): 时间转换 时间计算 序列化和反序列化:json,pickle 编解码:unicode,base64 加解密:md5,sha1,hmac_sha1,aes 常见装饰器: 计算执行时间装饰器 缓存装饰器 错误重试装饰器 延迟装饰器 尾递归优化装饰器 ini配置文件读取 代码整合如下: #!/usr/bin/env python # -*- coding: utf-8 -*- """ Created on 9/21/17 1:46 PM
职场亮哥
2020/10/10
4840
scrapy常用命令
scrapy常用的命令分为全局和项目两种命令,全局命令就是不需要依靠scrapy项目,可以在全局环境下运行,而项目命令需要在scrapy项目里才能运行。 一、全局命令 ##使用scrapy -h可以看到常用的全局命令 [root@aliyun ~]# scrapy -hScrapy 1.5.0 - no active project Usage: scrapy <command> [options] [args] Available commands: bench Run qui
IT架构圈
2018/06/01
7350
Python自动化部署
# -*- coding: utf-8 -*- #!/bin/env python ''' #Auth: karl #Function: released version #Date:2017/6/27 #Version:V1.0 ''' import  sys,re,os,time,datetime import  paramiko import logging import socket import ConfigParser import traceback from progressbar impo
py3study
2020/01/07
8260
码农技术炒股之路——数据库管理器、正则表达式管理器
        我选用的数据库是Mysql。选用它是因为其可以满足我的需求,而且资料多。因为作为第三方工具,难免有一些配置问题。所以本文也会讲解一些和Mysql配置及开发相关的问题。(转载请指明出于breaksoftware的csdn博客)
方亮
2019/01/16
6980
linux常用命令汇总_unix命令大全
for i in in {1..10}; do rm -f hadoop-cmf-hive-HIVEMETASTORE-nn1.testhdp.com.log.out.$i;done
全栈程序员站长
2022/11/09
6.2K0
linux常用命令汇总_unix命令大全
DDT框架结合单元测试
如果磁盘数据量大,一次性读取到内存,再读取到CPU,这样快点。每次启动磁盘读到内存再到CPU,CPU会等待磁盘读到数据,造成CPU资源的浪费。
清菡
2020/12/02
1.1K0
DDT框架结合单元测试
oracle 常用命令
在运行栏里面敲: sqlplus /nolog 回车 接着在弹出框里面敲:conn sys/password as sysdba回车(连接sys用户,加上 as sysdba,是以系统管理员的身份来登录的,如果是普通用户不需要as sysdba) 提示已连接 接着敲:alter user scott identified by tiger;回车(修改密码) 最后敲:alter user scott account unlock;回车(对SCOTT解锁)
Remember_Ray
2020/08/03
7760
python学习-SVN常用命令
SVN命令参考:http://riaoo.com/subpages/svn_cmd_reference.html
py3study
2020/01/08
1.9K0
相关推荐
python写的系统常用命令(一)
更多 >
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档
本文部分代码块支持一键运行,欢迎体验
本文部分代码块支持一键运行,欢迎体验