python 批量登陆

代码一:

#!/bin/env python2.7

import threading,paramiko,csv,sys


def inred( s ):
    return "%s[31;1m%s%s[0m"%(chr(27), s, chr(27))

try:
    file=raw_input("Chose the file.......:")
except:
    print""
try:
    cmd=raw_input("Input commands.......:")
except:
    print ""

if not cmd:
    print inred("There is no command and exit")
    sys.exit()

class cmdThread(threading.Thread):

    def __init__(self,ipadd,port,username,passwd):
        threading.Thread.__init__(self)
        self.ipadd = ipadd
        self.port = port
        self.username = username
        self.passwd = passwd

    def run(self):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        try:
            ssh.connect(str(self.ipadd), int(self.port),str(self.username),str(self.passwd),timeout=0.8)
        except:
            print "Can't connect "+self.ipadd+inred(" Please check it")
        else:
            stdin,stdout,stderr = ssh.exec_command(cmd)
            print self.ipadd+" is done; The result is :"+''.join(stdout.readlines())
            ssh.close()
try:
        Reader = csv.reader(open(file))
except Exception,e:
        print inred("There is no host filea, %s")  %(e)
        sys.exit()
for row in Reader:
    ipadd,port,username,passwd=row[0],row[1],row[2],row[3]
    thread = cmdThread(ipadd,port,username,passwd)
    thread.start()

 

 

代码二:

#!/usr/bin/python
#ssh.py
#coding:utf-8

import pexpect

def ssh_cmd(ip, port, user, passwd, cmd):
    ssh = pexpect.spawn('ssh -p %s %s@%s "%s"' % (port, user, ip, cmd))
    r = ''
    try:
        i = ssh.expect(['password: ', 'continue connecting (yes/no)?'])
        if i == 0 :
            ssh.sendline(passwd)
        elif i == 1:
            ssh.sendline('yes')
    except pexpect.EOF:
        ssh.close()
    else:
        r = ssh.read()
        ssh.expect(pexpect.EOF)
        ssh.close()
    return r


#for host in hosts.split("\n"):
for host in open("aa.txt"):
    if host:
        ip, port, user, passwd, cmds = host.split(":")
        for cmd in cmds.split(","):
            print "-- %s run:%s --" % (ip, cmd)
            print ssh_cmd(ip, port, user, passwd, cmd)

 

posted @ 2014-05-07 10:58  kingtigerhu  阅读(735)  评论(0)    收藏  举报