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中操作字符串之rstrip()方法的使用
May 19 Python
详解Python的Django框架中的模版继承
Jul 16 Python
Python脚本实现12306火车票查询系统
Sep 30 Python
使用Python的Scrapy框架十分钟爬取美女图
Dec 26 Python
利用python爬取软考试题之ip自动代理
Mar 28 Python
浅谈python函数之作用域(python3.5)
Oct 27 Python
python实现求解列表中元素的排列和组合问题
Mar 15 Python
Python文本统计功能之西游记用字统计操作示例
May 07 Python
使用Python来开发微信功能
Jun 13 Python
浅谈pytorch grad_fn以及权重梯度不更新的问题
Aug 20 Python
Python实现桌面翻译工具【新手必学】
Feb 12 Python
python实现过滤敏感词
May 08 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
德生H-501的评价与改造
2021/03/02 无线电
Aster vs KG BO3 第二场2.19
2021/03/10 DOTA
让mayfish支持mysqli数据库驱动的实现方法
2010/05/22 Javascript
关于div自适应高度/左右高度自适应一致的js代码
2013/03/22 Javascript
用js实现table单元格高宽调整,兼容合并单元格(兼容IE6、7、8、FF)实例
2013/06/25 Javascript
nodejs实现黑名单中间件设计
2014/06/17 NodeJs
new Date()问题在ie8下面的处理方法
2014/07/31 Javascript
原生js实现移动开发轮播图、相册滑动特效
2015/04/17 Javascript
浅谈Javascript数组的使用
2015/07/29 Javascript
js判断子窗体是否关闭的方法
2015/08/11 Javascript
几种二级联动案例(jQuery\Array\Ajax php)
2016/08/13 Javascript
JavaScript实现页面定时刷新(定时器,meta)
2016/10/12 Javascript
详解AngularJS ui-sref的简单使用
2017/04/24 Javascript
JS脚本加载后执行相应回调函数的操作方法
2018/02/28 Javascript
3分钟读懂移动端rem使用方法(推荐)
2019/05/06 Javascript
通过扫小程序码实现网站登陆功能
2019/08/22 Javascript
JavaScript字符串处理常见操作方法小结
2019/11/15 Javascript
基于scrapy实现的简单蜘蛛采集程序
2015/04/17 Python
python使用multiprocessing模块实现带回调函数的异步调用方法
2015/04/18 Python
python机器学习之决策树分类详解
2017/12/20 Python
Python SQLite3简介
2018/02/22 Python
pandas 对series和dataframe进行排序的实例
2018/06/09 Python
python实现支付宝转账接口
2019/05/07 Python
Python3 串口接收与发送16进制数据包的实例
2019/06/12 Python
小结Python的反射机制
2020/09/28 Python
Daisy London官网:英国最大的首饰集团IBB旗下
2019/02/28 全球购物
英国豪华家具和家居用品购物网站:Teddy Beau
2020/10/12 全球购物
标准导师推荐信(医学类)
2013/10/28 职场文书
毕业生求职自荐书范文
2014/03/27 职场文书
求职意向书范文
2014/04/01 职场文书
党员四风自我剖析材料思想汇报
2014/09/13 职场文书
校园歌手大赛主持词
2015/07/03 职场文书
2015初中团委工作总结
2015/07/28 职场文书
青年干部培训班学习心得体会
2016/01/06 职场文书
技术入股协议书
2016/03/22 职场文书
Python echarts实现数据可视化实例详解
2022/03/03 Python