Python uses the paramiko module to implement ssh remote login, upload files, and execute

Source: Internet
Author: User
Use paramiko and ssh to remotely log on and upload files and execute them. Multiple threads and queues are used. paramiko is a module written in python. it complies with the SSH2 protocol and supports remote server connection through encryption and authentication. When the program is executed, the hacker reads two files: command.txtand ipandpass.txt. The format is as follows:

The code is 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 a modified program, which is indeed well written.
This program is also positive and evil. if it is used to do bad things, I declare that it has nothing to do with me. I just want to share my code.
We hope that interested comrades will discuss technical applications.
Here, paramiko, queue, and multithreading are used, and some of these three things will be written in the future. Thank you for your criticism.
In fact, this program needs to be optimized in some places.

The code is as follows:


# Function: upload files through ssh protocal and excute the files
# Lib: paramiko
# MyThread: init a thread to run the 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)

Failed T 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
Failed T 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 t 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.exe c_command (comm ['alter _ auth'])
Ssh.exe c_command (comm ['exec _ program '])
Except t 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 t 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 t:
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)

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.