Python uses Paramiko module to implement SSH remote login upload file and execute _python

Source: Internet
Author: User
Tags sleep

Program execution requires reading two files Command.txt and ipandpass.txt. The format is as follows:

Copy Code code as follows:

Command.txt:
Threadnum:1
Port:22
Local_dir:hello_mkdir
Remote_dir:hello_mkdir
Alter_auth:chmod 755 Hello_mkdir
Exec_program:./hello_mkdir

Ipandpass.txt:
IP username Password

The queue operation in the program is another program that is modified, and it's really good to write.
The procedure is also evil, if you do bad things, I first declare that it has nothing to do with me, I just share my code.
Interested comrades are expected to discuss technology applications.
This is used in Paramiko, queues, multithreading, and the following will write some of these three things. Welcome to criticize and correct me.
In fact, some parts of this program have yet to be optimized.

Copy Code code as follows:

#function: Upload files through ssh protocal and excute the files
#lib:p Aramiko
#MyThread: Init a thread to run function
#ThreadPol: Init a thread pool
#uploadAndExecu: Upload file and Excute
#readConf: Read config file
#-*-coding = Utf-8-*-


Import Queue
Import Sys
Import threading
Import Paramiko
Import socket
From threading Import Thread
Import time

Class Mythread (Thread):
def __init__ (self, Workqueue, timeout=1):
Thread.__init__ (self)
Self.timeout = Timeout
Self.setdaemon (False)
Self.workqueue = Workqueue
Self.start ()
#print ' I am runnning ... '

def run (self):
Emptyqueue = 0
While True:
Try
Callable, username, password, ipaddress, Port,comms = self.workQueue.get (timeout = self.timeout)
#print ' attacking: ', Ipaddress,username,password,threading.currentthread (). GetName (), ' Time: '
Callable (Username,password, IPAddress, Port,comms)

Except Queue.empty:
Print Threading.currentthread (). GetName (), ": Queue is empty; Sleep 5 seconds\n "
Emptyqueue + 1
#judge the queue,if it is empty or not.
Time.sleep (5)
If Emptyqueue = 5:
Print Threading.currentthread (). GetName (), ' I quit,the queue is empty '
Break
Except Exception, error:
Print error

Class ThreadPool:
def __init__ (self, num_of_threads=10):
Self.workqueue = Queue.queue ()
Self.threads = []
Self.__createthreadpool (Num_of_threads)

#create The Threads Pool
def __createthreadpool (self, num_of_threads):
For I in Range (num_of_threads):
Thread = Mythread (self.workqueue)
Self.threads.append (thread)

def wait_for_complete (self):
#print Len (self.threads)
While Len (self.threads):
thread = Self.threads.pop ()
If Thread.isalive ():

Thread.Join ()

def add_job (self, callable, username, password, ipaddress, Port,comms):
Self.workQueue.put ((callable, username, password, ipaddress, Port,comms))

def UPLOADANDEXECU (Usernam,password,hostname,port,comm):
Print Usernam,password,hostname,port,comm
Try

t = Paramiko. Transport ((Hostname,int (port))
T.connect (Username=username,password=password)
Sftp=paramiko. Sftpclient.from_transport (t)
Sftp.put (comm[' local_dir '],comm[' Remote_dir ')]
Except Exception,e:
print ' Upload files failed: ', E
T.close ()
Finally
T.close ()


Try
SSH = Paramiko. Sshclient ()
Ssh.load_system_host_keys ()
Ssh.set_missing_host_key_policy (Paramiko. Missinghostkeypolicy ())
Ssh.connect (hostname, port=int (port), Username=username, Password=password)
Ssh.exec_command (comm[' Alter_auth ')
Ssh.exec_command (comm[' Exec_program ')
Except Exception,e:
print ' Chang file auth or execute the file failed: ', E
Ssh.close ()


Def readconf ():
comm={}
Try
f = File (' command.txt ', ' R ')
For L in F:
SP = L.split (': ')
Comm[sp[0]]=sp[1].strip (' \ n ')
Except Exception,e:
print ' Open file Command.txt failed: ', E
F.close ()

Return comm

if __name__ = = "__main__":

CommandLine = readconf ()
Print CommandLine
#prepare the IPs

WM = ThreadPool (int (commandline[' threadnum '))

Try
ipfile = File (' ipandpass.txt ', ' R ')
Except
Print [-] ip.txt Open file failed!
Sys.exit (1)

For line in Ipfile:
Ipadd,username,pwd = Line.strip (' \ r \ n '). Split (')
Wm.add_job (uploadandexecu,username,pwd,ipadd,commandline[' Port '],commandline)

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.