欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

python使用paramiko模块实现ssh远程登陆上传文件并执行

程序员文章站 2022-07-17 10:52:43
程序执行时需要读取两个文件command.txt和ipandpass.txt。格式如下: 复制代码 代码如下:command.txt:threadnum:1port:22...

程序执行时需要读取两个文件command.txt和ipandpass.txt。格式如下:

复制代码 代码如下:

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

程序中的队列操作是修改的别的程序,写的确实不错。
该程序亦正亦邪,如果拿去做坏事,我先声明与我无关,我只是分享我的代码罢了。
希望有兴趣的同志们来讨论技术应用。
这其中用到了paramiko,队列,多线程,后续也会写一些这三个方面的东西。欢迎批评指正。
其实这个程序有些地方还有待优化。

复制代码 代码如下:

#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)

            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)