退一步思路,关于paramiko

单一命令多服务器反馈,我之前写过fabric和pexpect的文章,这些都在Linux运行不错。但也有很多坑,尤其换到windows下坑点就多了

1.fabric本身的并行处理(-P参数)有bug,经常性抽风。而且在windows无法使用-P参数,效率大减
2.pexpect貌似不错,但是在windows下无法使用spawn方法。一样无用,可以参考官方文档http://pexpect.readthedocs.io/en/stable/overview.html#windows
stackoverflow例子
https://stackoverflow.com/questions/19389016/pexpect-cant-run-example-kept-getting-attributeerror-module-object-has-no

先贴出目前写的比较完美的pexpect脚本,以下用了threading来实现多线程,但输出采用的是pexpect.logfile的读取,相关密码会留在logfile里。不干净。然后最大的缺点就是windows下无法使用。

#!/usr/bin/python
#coding=utf-8

import pexpect
import getpass
import sys
import os
import time
from threading import Thread

class runmycmd(Thread):

  def __init__(self, userid, pwd, host, cmd, logdir):
     Thread.__init__(self)
     self.userid = userid
     self.pwd = pwd
     self.host = host
     self.cmd = cmd
     self.logdir = logdir
     
  def run(self):
     child = pexpect.spawn('ssh ' + self.userid + '@' + self.host + ' ' + self.cmd)
     tmphostlog = './' + self.logdir + '/' + self.host + '_tmp.log'
     file = open(tmphostlog,'wb')
     child.logfile = file
     index = child.expect(['[Pp]assword', '(yes/no)', pexpect.TIMEOUT])
     if index == 0:
        child.sendline(self.pwd)
     elif index == 1:
        child.sendline('yes')
        child.expect('[Pp]assword')
        child.sendline(self.pwd)
     else:
        child.close(force=True)
        print host + " : TIME OUT"
        return 1
     child.expect(pexpect.EOF)
     file.close()
     file = open(tmphostlog,'r')
     content = file.read()
     conlist = content.split('\n')
     while '' in conlist:
        conlist.remove('')
 
     for i in range(0,len(conlist)):
        if self.pwd not in conlist[i]:
           print self.host + ' : ' + conlist[i]
     file.close()

#调用过程
inputhosts = raw_input("input hosts,use [space] to split :")

hosts = inputhosts.split(" ")

userid = raw_input("input your id :")
pwd = getpass.getpass("input your password :")

cmd = raw_input("input your cmd :")

#log目录创建
todaydir = time.strftime('%Y%m%d',time.localtime())

if not os.path.exists(todaydir):
   os.makedirs(todaydir)

T_thread=[]
for host in hosts:
  t=runmycmd(userid,pwd,host,cmd,todaydir)
  T_thread.append(t)
#print T_thread
for i in range(len(T_thread)):
  T_thread[i].start()

所以,能否采用退一步思考方式,就是paramiko这个模块

写出来是这样

#!/usr/bin/python
#coding=utf-8

import paramiko
import getpass
import sys
import os
import time
from threading import Thread

class runmycmd(Thread):

  def __init__(self, userid, pwd, host, cmd):
     Thread.__init__(self)
     self.userid = userid
     self.pwd = pwd
     self.host = host
     self.cmd = cmd
     
  def run(self):
    ssh = paramiko.SSHClient()
    ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    ssh.connect(hostname=self.host, port=22, username=self.userid, password=self.pwd)
    stdin,stdout,stderr = ssh.exec_command(self.cmd)
    result = str(stdout.read())[2:]
    resultlist = result.split('\\n')

    for line in resultlist:
       hostline = self.host + " : " + line
       print(hostline)
       
    ssh.close()

#调用过程
inputhosts = input("input hosts,use [space] to split :")

hosts = inputhosts.split(" ")

userid = input("input your id :")
pwd = getpass.getpass("input your password :")

cmd = input("input your cmd :")

T_thread=[]
for host in hosts:
  t=runmycmd(userid,pwd,host,cmd)
  T_thread.append(t)
#print T_thread
for i in range(len(T_thread)):
  T_thread[i].start()

执行效果如下

PS C:\Users\Administrator\Desktop\python_script> python .\parainfo.py
input hosts,use [space] to split :amainst anodest01 anodest02
input your id :vagrant
input your password :
input your cmd :uname -n
amainst : amainst
amainst : '
anodest01 : anodest01
anodest01 : '
anodest02 : anodest02
anodest02 : '
PS C:\Users\Administrator\Desktop\python_script>

至于多余的数据(那个')可以自己在脚本中修改stdout.read()

你可能感兴趣的:(退一步思路,关于paramiko)