#!/usr/bin/env python
#coding =utf-8
Import Paramiko
Import time,datetime,threading
def SSH (ip,user,passwd,command):
ssh = Paramiko. Sshclient ()
Ssh.set_missing_host_key_policy (Paramiko. Autoaddpolicy ())
Try:
Ssh.connect (IP,PORT=16333,USERNAME=USER,PASSWORD=PASSWD)
except Paramiko. Authenticationexception:
#print "Authentication failed, user name or password is incorrect."
return 0
except:
#print ' IP ', ' Host unreachable '. "
return 2
stdin, stdout, stderr = Ssh.exec_command (command)
lines = [Line.strip () for line in Stdout.readlines ()]
data_include_firstline = "". Join (lines)
data_no_firstline = "". Join (lines[1:])
return Data_include_firstline
def sshcmd (src,linerange):
i = 0
For line in Open (SRC):
i + = 1
if I in range (linerange[0],linerange[1]+1):
IP = line.strip ()
user = ' root '
Port = 16333
passwd = ' 123qwe '
command = ' hostname '
result = SSH (Ip,user,passwd,command)
if result = = 0:
result = ' validation failed, user name or password error. '
elif result = = 2:
result = ' host unreachable. '
Print I,ip,result
def Main (NUM,SRC):
global count, mutex
linesum = SUM (1 for line in open (SRC))
quotient = Linesum/num
threads = []
# Create a lock
Mutex = Threading. Lock ()
# Create thread objects First
for K in xrange (1, num+1):
if k = = num:
Linerange = quotient* (k-1) +1,linesum
Else:
Linerange = quotient* (k-1) +1,quotient*k
Threads.append (Threading. Thread (Target=sshcmd, args= (Src,linerange)))
# start All Threads
For T in Threads:
T.start ()
# Wait for all child threads to exit in the main thread
For T in Threads:
T.join ()
starttime = Datetime.datetime.now ()
if __name__ = = ' __main__ ':
# Create 10 threads
Main (Ten, ' Ip.txt ')
endtime = Datetime.datetime.now ()
print "Time span", Endtime-starttime
This article is from the "I am a Little bird" blog, please make sure to keep this source http://2242558.blog.51cto.com/2232558/1545306
Python via threading multi-threaded SSH