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中操作MySQL入门实例
Feb 08 Python
详解Python3中的Sequence type的使用
Aug 01 Python
pyQt4实现俄罗斯方块游戏
Jun 26 Python
Python unittest单元测试框架总结
Sep 08 Python
python多线程并发让两个LED同时亮的方法
Feb 18 Python
Django基础知识 web框架的本质详解
Jul 18 Python
mac在matplotlib中显示中文的操作方法
Mar 06 Python
python实现简单坦克大战
Mar 27 Python
Django中F函数的使用示例代码详解
Jul 06 Python
Python代码覆盖率统计工具coverage.py用法详解
Nov 25 Python
python爬虫beautifulsoup解析html方法
Dec 07 Python
python可视化之颜色映射详解
Sep 15 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
PHP调用三种数据库的方法(2)
2006/10/09 PHP
PHP 数组基础知识小结
2010/08/20 PHP
php下获取http状态的实现代码
2014/05/09 PHP
如何使用PHP给图片加水印
2016/10/12 PHP
html读出文本文件内容
2007/01/22 Javascript
input+select(multiple) 实现下拉框输入值
2009/05/21 Javascript
修复IE9&safari 的sort方法
2011/10/21 Javascript
获得Javascript对象属性个数的示例代码
2013/11/21 Javascript
JavaScript截取、切割字符串的技巧
2016/01/07 Javascript
jquery自定义插件结合baiduTemplate.js实现异步刷新(附源码)
2016/12/22 Javascript
js实现移动端导航点击自动滑动效果
2017/07/18 Javascript
微信小程序-滚动消息通知的实例代码
2017/08/03 Javascript
JS+HTML+CSS实现轮播效果
2017/11/28 Javascript
js统计页面上每个标签的数量实例代码
2018/05/29 Javascript
JavaScript设计模式之代理模式实例分析
2019/01/16 Javascript
微信小程序缓存过期时间的使用详情
2019/05/12 Javascript
[46:20]CHAOS vs Alliacne 2019国际邀请赛小组赛 BO2 第二场 8.15
2019/08/16 DOTA
Python实现将n个点均匀地分布在球面上的方法
2015/03/12 Python
Python随机生成带特殊字符的密码
2016/03/02 Python
Python实现一个转存纯真IP数据库的脚本分享
2017/05/21 Python
Python中Proxypool库的安装与配置
2018/10/19 Python
python 读取鼠标点击坐标的实例
2018/12/29 Python
分享8个非常流行的 Python 可视化工具包
2019/06/05 Python
Django集成CAS单点登录的方法示例
2019/06/10 Python
Django用户认证系统 User对象解析
2019/08/02 Python
使用python将最新的测试报告以附件的形式发到指定邮箱
2019/09/20 Python
使用OpenCV对车道进行实时检测的实现示例代码
2020/06/19 Python
Python3爬虫中识别图形验证码的实例讲解
2020/07/30 Python
HTML5 CSS3新的WEB标准和浏览器支持
2009/07/16 HTML / CSS
客户代表自我评价范例
2013/09/24 职场文书
如何写你的创业计划书
2014/01/07 职场文书
初婚未育证明样本
2014/10/24 职场文书
2014年仓库保管员工作总结
2014/12/03 职场文书
合理化建议书
2015/02/04 职场文书
工作收入证明范本
2015/06/12 职场文书
导游词之临安白水涧
2019/11/05 职场文书