美文网首页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--命令行执行加参数

    写一个简易版的ansible指日可待!实现了指定参数的脚本,先改造了exec模块;这一版本还要继续优化;后面继续整...

  • 命令行实战

    命令行调用 php 执行think 脚本名 参数1 参数2 参数3 php /www/wwwroot/newCen...

  • 命令行参数和可变参数

    命令行参数 String[] args 数组 通过执行 java 运行配置传递参数: java HelloWorl...

  • 8.文件操作

    // 命令行参数 // 命令行参数用于向程序传递在执行阶段才确定的数据 // 提升软件的可移植行 int main...

  • Scrapy命令行动态传参给spider

    scrapy命令行执行传递多个参数给spider 动态传参 在命令行运行scrapy爬虫 若爬虫中有参数可以控制爬...

  • GetoptLong简单例子

    1 GetoptLong GetoptLong主要是用来处理命令行参数。 示例代码: 命令行调用: 执行结果:

  • jmeter 生成jtl文件格式以及内容包含request、re

    ​如下两种方式都可以: 1、添加命令行参数 在命令行执行的时候加入如下参数即可 -Jjmeter.save.sav...

  • UNIX进程的环境(二)

    2016-02-02 命令行参数 当执行一个程序时,调用exec的进程可将命令行参数传递给该新程序。其中argv[...

  • shell中处理用户输入

    1、使用命令行参数在shell执行的时候命令行中输入的所有参数可以赋值给一些特殊变量,这些变量成为位置变量参数。包...

  • [总结] npm使用备忘

    设置国内registry,加快下载速度 临时设置访问源,命令行输入: 命令行中直接加registry参数。 若想永...

网友评论

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

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