红色多瑙河 发表于 2018-8-3 12:36:29

批量管理python脚本

  新出炉的脚本, 有错的地方还望指出,谢谢。
  #!/usr/bin/env python
  # -*- coding: utf-8 -*-
  #
  #Syscloud Operation platform.py
  #
  #Copyright 2013 allan <allan@ALLAN-PC>
  #
  #This program 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., 51 Franklin Street, Fifth Floor, Boston,
  #MA 02110-1301, USA.
  #
  #QQ:286575330
  import paramiko
  import sys
  import Queue
  import threading
  import getopt
  class webmonitor:
  def __init__(self):
  try:
  self.pkey_file=‘这是密钥的路径’
  self.known_host = '/root/.ssh/known_hosts'
  self.key=paramiko.RSAKey.from_private_key_file(self.pkey_file, password=‘这里是密钥的密码’)
  except:
  print 'No such file or directory: \'/root/.ssh/jumper_rsa\''
  def help(self):
  return '''
  -h,--help            帮助页面
  -c,--command      执行的命令
  -H,--host            主机IP
  -f, --file      指定文件
  -S, --SENDFILE    传输文件模式
  -C, --COMMAND      执行命令模式
  -L, --localpath    本地文件路径
  -R, --removepath    远程服务器路径
  e.g.
  单台执行命令格式: -C -H “IP地址” -c “命令”
  批量执行命令格式: -C -f “IP地址文件” -c “命令”
  单台传送文件: -S -H “IP地址” -L &quot;本地文件路径&quot; -R “远程服务器文件路径”
  批量传送文件: -S -f &quot;IP地址文件&quot; -L “本地文件路径” -R “远程文件路径”
  '''
  def ssh(self,hostname,port,username, cmd):#ssh 远程执行命令
  ssh = paramiko.SSHClient()
  ssh.load_system_host_keys(self.known_host)
  ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
  ssh.connect(hostname, port, username, password='这是远程服务器密码', pkey=self.key, allow_agent=True, look_for_keys=True)
  stdin, stdout, stderr = ssh.exec_command(cmd)
  if stderr.read() != 0:
  print '%s%s\n%s\n' % (stderr.read(),stdout.read(),hostname)
  print '========================================================================='
  else:
  print &quot;\033%s\033[0m&quot; % hostname
  print '========================================================================='
  ssh.close()
  def sftp(self, hostname, port,username,localpath, remotepath):#SFTP 传输文件
  ssh = paramiko.Transport((hostname,port))
  ssh.connect(username=username, pkey=self.key)
  sftp = paramiko.SFTPClient.from_transport(ssh)
  sftp.put(localpath,remotepath)
  sftp.close()
  ssh.close()
  print '========================================================================='
  print &quot;OK %s&quot; % hostname
  return 0
  def isset(v):#判断定义的是否为变量
  try:
  type (eval(v))
  except:
  return 0
  else:
  return 1
  if __name__ == '__main__':
  try:
  opts, args = getopt.getopt(sys.argv, &quot;L:R:CSH:c:f:h&quot;, [&quot;localpath&quot;,&quot;remotepath&quot;,&quot;COMMAND&quot;,&quot;SENDFILE&quot;,&quot;host&quot;,&quot;command&quot;,&quot;file&quot;,'help'])
  if sys.argv == &quot;-S&quot;:
  for o, value in opts:
  if o in (&quot;-S&quot;,&quot;--SENDFILE&quot;):
  print &quot;MODE: SENDFILE&quot;
  elif o in (&quot;-h&quot;,&quot;--help&quot;):
  print webmonitor().help()
  elif o in (&quot;-H&quot;,&quot;--host&quot;):
  host = value
  elif o in (&quot;-f&quot;, &quot;--file&quot;):
  filein = value
  elif o in (&quot;-c&quot;,&quot;--command&quot;):
  cmd = value
  elif o in (&quot;-R&quot;,&quot;--remotepath&quot;):
  rpath = value
  elif o in (&quot;-L&quot;,&quot;--localpath&quot;):
  lpath = value
  if isset('host') and isset('lpath') and isset('rpath'):
  webmonitor().sftp(host, 22, &quot;root&quot;, lpath, rpath)
  print '========================================================================='
  elif isset('filein') and isset('lpath') and isset('rpath'):
  threads = []
  myqueue = Queue.Queue(maxsize = 0)
  f = open(filein, &quot;r&quot;)
  for ip in f:
  if ip == '#':
  break
  if len(ip) == 0:
  break
  myqueue.put(ip)
  f.close()
  for x in xrange(0,myqueue.qsize()):
  if myqueue.empty():
  break
  mutex = threading.Lock()
  mutex.acquire()
  threads.append(threading.Thread(target=webmonitor().sftp, args=(myqueue.get(),22,&quot;root&quot;, lpath, rpath)))
  mutex.release()
  for t in threads:
  t.start()
  for t in threads:
  t.join()
  print '========================================================================='
  elif sys.argv == &quot;-C&quot;:#执行命令模式
  for o, value in opts:
  if o in (&quot;-C&quot;,&quot;--COMMAND&quot;):
  print &quot;MODE: COMMAND&quot;
  elif o in (&quot;-H&quot;,&quot;--host&quot;):
  host = value
  elif o in (&quot;-f&quot;,&quot;--file&quot;):
  filein = value
  elif o in (&quot;-c&quot;,&quot;--command&quot;):
  cmd = value
  if isset('host') and isset('cmd'):#单台服务器执行命令
  webmonitor().ssh(host, 22, &quot;root&quot;, cmd)
  elif isset('filein') and isset('cmd'):#多台服务器批量执行命令
  threads = []
  myqueue = Queue.Queue(maxsize = 0)
  f = open(filein, &quot;r&quot;)
  for ip in f:
  if ip == '#':
  break
  if len(ip) == 0:
  break
  myqueue.put(ip)
  f.close()
  for x in xrange(0,myqueue.qsize()):
  if myqueue.empty():#判断队列是否为空
  break
  mutex = threading.Lock()
  mutex.acquire()
  threads.append(threading.Thread(target=webmonitor().ssh, args=(myqueue.get(),22,&quot;root&quot;, cmd)))
  mutex.release()
  for t in threads:
  t.start()
  for t in threads:
  t.join()
  else:
  print webmonitor().help()
  except:
  print webmonitor().help()
页: [1]
查看完整版本: 批量管理python脚本