您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

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

5b51 2022/1/14 8:18:02 python 字数 8872 阅读 338 来源 www.jb51.cc/python

程序执行时需要读取两个文件command.txt和ipandpass.txt。格式如下: 复制代码代码如下:command.txt:ThreadNum:1port:22local_dir:hello_mkdirremote_dir:hello_mkdiralter_auth:chmod755hello_mkdirexec_program:./

概述

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

ipandpass.txt:
ip username password

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


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 :',threading.currentThread().getName(),' time : '
                callable(username,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,Port,comms):
        self.workQueue.put((callable,comms))

def uploadAndExecu(usernam,hostname,comm):
    print usernam,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,pwd = line.strip('\r\n').split(' ')
        wm.add_job(uploadAndExecu,pwd,IpAdd,commandLine['port'],commandLine)

总结

以上是编程之家为你收集整理的python使用paramiko模块实现ssh远程登陆上传文件并执行全部内容,希望文章能够帮你解决python使用paramiko模块实现ssh远程登陆上传文件并执行所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶