美文网首页Python
python3--命令行执行加参数

python3--命令行执行加参数

作者: w_dll | 来源:发表于2020-09-23 12:28 被阅读0次

    写一个简易版的ansible指日可待!
    实现了指定参数的脚本,先改造了exec模块;
    这一版本还要继续优化;后面继续整合;
    这一版本用python3 是为了引入argparse模块;
    之前python2 和 python3 都是兼容的。

    脚本 --help

    2020-09-27 更新

    增加了 -c模块,增加了一些容错性

    #!/usr/bin/python3
    # date : 2020-09-27
    # v3 : add command , some errors catch
    import os, shutil, argparse, sys, time, threading
    import subprocess
    
    #BASE_DIR = os.getcwd()
    BASE_DIR = sys.path[0]
    os.chdir(BASE_DIR)
    if not os.path.isdir('tmp'):
        os.makedirs('tmp')
    TMP_DIR = os.path.join(BASE_DIR, 'tmp')
    IP_FILE = os.path.join(TMP_DIR, 'ip.txt')
    
    TMP_FILE = os.path.join(TMP_DIR, 'tmp.sh')
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-i", "--ip_file", help="ip文件", type=str, default=IP_FILE)
    parser.add_argument("-ip", "--ip", help="ip", type=str, default=IP_FILE)
    parser.add_argument("-e", "--exec_file", help="执行文件", type=str, default=TMP_FILE)
    parser.add_argument("-c", "--command", help="执行文件", type=str, default=TMP_FILE)
    args = parser.parse_args()
    exec_file = args.exec_file
    exec_command = args.command
    
    def gen_ip_fun():
        ip_file = 'None'
        if args.ip != IP_FILE and args.ip_file != IP_FILE:
            print("不能同时指定-i和-ip参数")
            sys.exit()
        elif args.ip != IP_FILE:
            f = open(IP_FILE, "w")
            this_str = str(args.ip)
            f.write(this_str)
            f.close()
        elif args.ip_file != IP_FILE:
            ip_file = str(args.ip_file)
            if os.path.isfile(ip_file):
                shutil.copy(str(ip_file), IP_FILE)
            else:
                print('not exists!')
                sys.exit()
        else:
            ip_file = IP_FILE
        ip_file = IP_FILE
        if ip_file == 'None':
            print('ip file error!')
            sys.exit()
    
    
    
    def gen_exec_fun():
        if str(exec_file) != str(TMP_FILE) and str(exec_command) != str(TMP_FILE):
            print("不能同时指定-c和-e参数")
            sys.exit()
        elif str(exec_file) != str(TMP_FILE):
            source = str(exec_file)
            target = TMP_FILE
            shutil.copy(source, target)
        elif str(exec_command) != str(TMP_FILE):
            f = open(TMP_FILE, "w")
            f.write(str(exec_command))
            f.close()
    
    
    class myThread (threading.Thread):
        def __init__(self, exec_file, name, tinfo):
            threading.Thread.__init__(self)
            self.exec_file = exec_file
            self.name = name
            self.tinfo = tinfo
        def run(self):
            this_ip = str(self.name)
            this_str="start :" + str(this_ip)
            print (this_str)
            try :
                command = "scp -o ConnectTimeout=5 -q -r " + str(self.exec_file)  + " root@" +  str(this_ip) + ":/home"
                res = subprocess.run(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8",timeout=2)
            except Exception as e:
                error_info = "===> :" + str(self.tinfo) + "\nerror info: " + str(e) + "\n\n"
                print(error_info)
                return False
            else :
                res = os.popen(('ssh root@%s  -o ConnectTimeout=5 "cd /home;bash tmp.sh; rm -f tmp.sh"') % (str(this_ip))).read()
                this_str = "===> :" + str(self.tinfo) + "\n" + str(res) + "\n\n"
                print (this_str)
    
    if __name__ == '__main__':
        gen_exec_fun()
        gen_ip_fun()
        ip_lists = []
        #ip_file = open('ip.txt', 'rb')
        ip_file = open(ip_file, 'rb')
    
        machines_info = []
    
        for li in ip_file :
          if li and '#' not in str(li):
            machines_info.append(str(li))
            li = str(li).split()
            li = li[0]
            ip_lists.append(str(li))
        ip_file.close()
    
        #max_tasks = input('请输入并行个数:')
        max_tasks = 10
        while ip_lists :
          this_ip_lists = []
          for li in range(max_tasks) :
            if ip_lists :
              this_ip = ip_lists.pop(0)
              this_ip_lists.append(str(this_ip))
          this_threads = []
          for ip in this_ip_lists :
            for li_m in machines_info :
              if ip in li_m:
                this_info = str(li_m)
                this_info = str(li_m).split( '\'' )
                this_info = this_info[1]
                this_info = this_info.split( '\\' )
                this_info = this_info[0]
            t_ip = str(ip).split( '\'' )
            t_ip = t_ip[1]
            t_exec_file = str(TMP_FILE)
            t_name = myThread(t_exec_file, t_ip, this_info)
            this_threads.append(t_name)
          [ thr.start() for thr in this_threads ]
          [ thr.join() for thr in this_threads ]
          print('-----------------------------------------')
    
    

    脚本内容

    ---- 修复了一些问题,引用了subprocess模块,expect异常可以获取了

    #!/usr/bin/python3
    # date : 2020-09-23
    # v2 : add argparse
    import os, shutil, argparse, sys, time, threading
    import subprocess
    
    BASE_DIR = os.getcwd()
    if not os.path.isdir('tmp'):
        os.makedirs('tmp')
    TMP_DIR = os.path.join(BASE_DIR, 'tmp')
    IP_FILE = os.path.join(TMP_DIR, 'ip.txt')
    
    TMP_FILE = os.path.join(TMP_DIR, 'tmp.sh')
    
    parser = argparse.ArgumentParser()
    parser.add_argument("-if", "--ip_file", help="ip文件", type=str, default=IP_FILE)
    parser.add_argument("-i", "--ip", help="ip", type=str, default=IP_FILE)
    parser.add_argument("-e", "--exec_file", help="执行文件", type=str, default=TMP_FILE)
    args = parser.parse_args()
    exec_file = args.exec_file
    
    ip_file = 'None'
    if args.ip != IP_FILE:
        f = open(IP_FILE, "w")
        this_str = str(args.ip)
        f.write(this_str)
        f.close()
    elif args.ip_file != IP_FILE:
        ip_file = str(args.ip_file)
        if os.path.isfile(ip_file):
            shutil.copy(str(ip_file), IP_FILE)
        else:
            print('not exists!')
    else:
        ip_file = IP_FILE
    
    ip_file = IP_FILE
    
    if ip_file == 'None':
        print('ip file error!')
    
    source = str(exec_file)
    target = TMP_FILE
    shutil.copy(source, target)
    
    class myThread (threading.Thread):
        def __init__(self, exec_file, name, tinfo):
            threading.Thread.__init__(self)
            self.exec_file = exec_file
            self.name = name
            self.tinfo = tinfo
        def run(self):
            this_ip = str(self.name)
            this_str="start :" + str(this_ip)
            print (this_str)
            try :
                command = "scp -o ConnectTimeout=5 -q -r " + str(self.exec_file)  + " root@" +  str(this_ip) + ":/home"
                res = subprocess.run(command,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE,encoding="utf-8",timeout=2)
            except Exception as e:
                error_info = "===> :" + str(self.tinfo) + "\n" + str(e) + "\n\n"
                print(error_info)
                return False
            else :
                res = os.popen(('ssh root@%s  -o ConnectTimeout=5 "cd /home;bash tmp.sh; rm -f tmp.sh"') % (str(this_ip))).read()
                this_str = "===> :" + str(self.tinfo) + "\n" + str(res) + "\n\n"
                print (this_str)
    
    if __name__ == '__main__':
        ip_lists = []
        #ip_file = open('ip.txt', 'rb')
        ip_file = open(ip_file, 'rb')
    
        machines_info = []
    
        for li in ip_file :
          if li and '#' not in str(li):
            machines_info.append(str(li))
            li = str(li).split()
            li = li[0]
            ip_lists.append(str(li))
        ip_file.close()
    
        #max_tasks = input('请输入并行个数:')
        max_tasks = 10
        while ip_lists :
          this_ip_lists = []
          for li in range(max_tasks) :
            if ip_lists :
              this_ip = ip_lists.pop(0)
              this_ip_lists.append(str(this_ip))
          this_threads = []
          for ip in this_ip_lists :
            for li_m in machines_info :
              if ip in li_m:
                this_info = str(li_m)
                this_info = str(li_m).split( '\'' )
                this_info = this_info[1]
                this_info = this_info.split( '\\' )
                this_info = this_info[0]
            t_ip = str(ip).split( '\'' )
            t_ip = t_ip[1]
            t_exec_file = str(target)
            t_name = myThread(t_exec_file, t_ip, this_info)
            this_threads.append(t_name)
          [ thr.start() for thr in this_threads ]
          [ thr.join() for thr in this_threads ]
          print('-----------------------------------------')
    
    

    ---- 旧版

    #!/usr/bin/python3
    # date : 2020-09-23
    # v2 : add argparse
    import os, shutil, argparse, sys, time, threading
    
    BASE_DIR = os.getcwd()
    if not os.path.isdir('tmp'):
        os.makedirs('tmp')
    TMP_DIR = os.path.join(BASE_DIR, 'tmp')
    IP_FILE = os.path.join(TMP_DIR, 'ip.txt')
    TMP_FILE = os.path.join(TMP_DIR, 'tmp.sh')
    
    parser = argparse.ArgumentParser()
    #parser.add_argument("-s", "--src", help="source file", type=str)
    #parser.add_argument("-t", "--tar", help="target dir", type=str)
    #parser.add_argument("-i", "--ip", help="单个ip", action='store_true', type=str, default='ip.txt')
    parser.add_argument("-if", "--ip_file", help="ip文件", type=str, default=IP_FILE)
    parser.add_argument("-i", "--ip", help="ip", type=str, default=IP_FILE)
    parser.add_argument("-e", "--exec_file", help="执行文件", type=str, default=TMP_FILE)
    
    args = parser.parse_args()
    #source = args.src
    #target = args.tar
    exec_file = args.exec_file
    ip_file = 'ip -- error input!'
    if args.ip != IP_FILE:
        ip_file = args.ip
    elif args.ip_file != IP_FILE:
        ip_file = str(args.ip_file)
        #if os.path.exists(file_name):
        if os.path.isfile(ip_file):
            ip_file = args.ip_file
        else:
            print('not exists!')
    else:
        ip_file = args.ip_file
    
    source = str(exec_file)
    target = TMP_FILE
    shutil.copy(source, target)
    
    #print(source)
    #print(target)
    #print(ip)
    
    
    
    class myThread (threading.Thread):
        #def __init__(self, threadID, name, tinfo):
        def __init__(self, exec_file, name, tinfo):
            threading.Thread.__init__(self)
            #self.threadID = threadID
            self.exec_file = exec_file
            self.name = name
            self.tinfo = tinfo
        def run(self):
            this_ip = str(self.name)
            this_str="start :" + str(this_ip)
            print (this_str)
            os.system(('scp -q %s root@%s:/home') % (str(self.exec_file), str(this_ip)))
            #os.system(('scp -q log/tmp.sh root@%s:/home') % (str(self.name)))
            #res = os.system(('ssh root@%s "cd /home;bash tmp.sh; rm -f tmp.sh"') % (str(self.name)))
            res = os.popen(('ssh root@%s "cd /home;bash tmp.sh; rm -f tmp.sh"') % (str(this_ip))).read()
            this_str = "===> :" + str(self.tinfo) + '\n' + str(res) + '\n\n'
            print (this_str)
    
    
    ip_lists = []
    #ip_file = open('ip.txt', 'rb')
    ip_file = open(ip_file, 'rb')
    
    machines_info = []
    
    for li in ip_file :
      if li :
        machines_info.append(str(li))
        li = str(li).split()
        li = li[0]
        ip_lists.append(str(li))
    ip_file.close()
    
    #max_tasks = input('请输入并行个数:')
    max_tasks = 10
    while ip_lists :
      this_ip_lists = []
      for li in range(max_tasks) :
        if ip_lists :
          this_ip = ip_lists.pop(0)
          this_ip_lists.append(str(this_ip))
      this_threads = []
      for ip in this_ip_lists :
        for li_m in machines_info :
          if ip in li_m :
            this_info = str(li_m)
            this_info = str(li_m).split( '\'' )
            this_info = this_info[1]
            this_info = this_info.split( '\\' )
            this_info = this_info[0]
        t_ip = str(ip).split( '\'' )
        t_ip = t_ip[1]
        t_exec_file = str(target)
        t_name = myThread(t_exec_file, t_ip, this_info)
        this_threads.append(t_name)
      [ thr.start() for thr in this_threads ]
      [ thr.join() for thr in this_threads ]
      print('-----------------------------------------')
    

    执行结果

    相关文章

      网友评论

        本文标题:python3--命令行执行加参数

        本文链接:https://www.haomeiwen.com/subject/ojanyktx.html