Python via threading multi-threaded SSH

Source: Internet
Author: User
Tags exit in

#!/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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.