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


Posted in Python onJanuary 27, 2014

程序执行时需要读取两个文件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)
Python 相关文章推荐
Python中使用dom模块生成XML文件示例
Apr 05 Python
Python socket编程实例详解
May 27 Python
Ruby元编程基础学习笔记整理
Jul 02 Python
Python图片裁剪实例代码(如头像裁剪)
Jun 21 Python
浅谈Python由__dict__和dir()引发的一些思考
Oct 30 Python
CentOS 6.5中安装Python 3.6.2的方法步骤
Dec 03 Python
python类的方法属性与方法属性的动态绑定代码详解
Dec 27 Python
python如何删除文件中重复的字段
Jul 16 Python
Python requests模块cookie实例解析
Apr 14 Python
Python configparser模块封装及构造配置文件
Aug 07 Python
Python 整行读取文本方法并去掉readlines换行\n操作
Sep 03 Python
Python基础知识学习之类的继承
May 31 Python
python list使用示例 list中找连续的数字
Jan 27 #Python
Python批量修改文件后缀的方法
Jan 26 #Python
使用cx_freeze把python打包exe示例
Jan 24 #Python
Python的函数嵌套的使用方法
Jan 24 #Python
下载安装setuptool和pip linux安装pip    
Jan 24 #Python
python解析文件示例
Jan 23 #Python
python回调函数的使用方法
Jan 23 #Python
You might like
ThinkPHP中URL路径访问与模块控制器之间的关系
2014/08/23 PHP
PHP和C#可共用的可逆加密算法详解
2015/10/26 PHP
thinkPHP中配置的读取与C方法详解
2016/12/05 PHP
PHP实现支付宝即时到账功能
2016/12/21 PHP
thinkphp项目如何自定义微信分享描述内容
2017/02/20 PHP
PHP微信H5支付开发实例
2018/07/25 PHP
javascript 中对象的继承〔转贴〕
2007/01/22 Javascript
关于js datetime的那点事
2011/11/15 Javascript
浅谈javascript中for in 和 for each in的区别
2015/04/23 Javascript
javascript实现状态栏文字首尾相接循环滚动的方法
2015/07/22 Javascript
深入JavaScript高级程序设计之对象、数组(栈方法,队列方法,重排序方法,迭代方法)
2015/12/01 Javascript
Bootstrap与KnockoutJs相结合实现分页效果实例详解
2016/05/03 Javascript
JSONP原理及简单实现
2016/06/08 Javascript
Javascript类型系统之undefined和null浅析
2016/07/13 Javascript
JS实现“隐藏与显示”功能(多种方法)
2016/11/24 Javascript
利用node.js写一个爬取知乎妹纸图的小爬虫
2017/05/03 Javascript
vue引入swiper插件的使用实例
2017/07/19 Javascript
nuxt+axios解决前后端分离SSR的示例代码
2017/10/24 Javascript
利用VS Code开发你的第一个AngularJS 2应用程序
2017/12/15 Javascript
vue.js input框之间赋值方法
2018/08/24 Javascript
Vue实现手机号、验证码登录(60s禁用倒计时)
2020/12/19 Vue.js
[00:33]2016完美“圣”典风云人物:BurNIng宣传片
2016/12/10 DOTA
Python实现将n个点均匀地分布在球面上的方法
2015/03/12 Python
Django使用Celery异步任务队列的使用
2018/03/13 Python
详解flask表单提交的两种方式
2018/07/21 Python
pytorch模型存储的2种实现方法
2020/02/14 Python
html5使用canvas实现跟随光标跳动的火焰效果
2014/01/07 HTML / CSS
历史学专业毕业生求职信
2013/09/27 职场文书
《有趣的发现》教学反思
2014/04/15 职场文书
综治工作心得体会
2014/09/11 职场文书
销售督导岗位职责
2015/04/10 职场文书
反邪教警示教育活动总结
2015/05/09 职场文书
入党积极分子党支部意见
2015/06/02 职场文书
QT与javascript交互数据的实现
2021/05/26 Javascript
用python基于appium模块开发一个自动收取能量的小助手
2021/09/25 Python
python神经网络ResNet50模型
2022/05/06 Python