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从零实现贝叶斯分类器的机器学习的教程
Mar 31 Python
Python中的Classes和Metaclasses详解
Apr 02 Python
举例详解Python中的split()函数的使用方法
Apr 07 Python
用Python脚本来删除指定容量以上的文件的教程
May 04 Python
Python中的urllib模块使用详解
Jul 07 Python
python在非root权限下的安装方法
Jan 23 Python
Tensorflow的可视化工具Tensorboard的初步使用详解
Feb 11 Python
致Python初学者 Anaconda入门使用指南完整版
Apr 05 Python
python pytest进阶之xunit fixture详解
Jun 27 Python
Python爬虫 urllib2的使用方法详解
Sep 23 Python
如何用Python 实现全连接神经网络(Multi-layer Perceptron)
Oct 15 Python
4种方法python批量修改替换列表中元素
Apr 07 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
一个颜色轮换的简单例子
2006/10/09 PHP
destoon后台网站设置变成空白的解决方法
2014/06/21 PHP
php实现留言板功能(代码详解)
2017/03/28 PHP
动态刷新 dorado树的js代码
2009/06/12 Javascript
js的一些常用方法小结
2011/06/29 Javascript
浅谈js中的闭包
2015/03/16 Javascript
jQuery实现MSN中文网滑动Tab菜单效果代码
2015/09/09 Javascript
BootStrap 智能表单实战系列(十)自动完成组件的支持
2016/06/13 Javascript
浅析JavaScript中作用域和作用域链
2016/12/06 Javascript
AngularJS实现自定义指令与控制器数据交互的方法示例
2017/06/19 Javascript
详解Angular 自定义结构指令
2017/06/21 Javascript
如何选择适合你的JavaScript框架
2017/11/20 Javascript
LayerClose弹窗关闭刷新方法
2018/08/17 Javascript
基于iview-admin实现动态路由的示例代码
2019/10/02 Javascript
js 递归json树实现根据子id查父id的方法分析
2019/11/08 Javascript
Vue 实现一个简单的鼠标拖拽滚动效果插件
2020/12/10 Vue.js
Python生成pdf文件的方法
2014/08/04 Python
python快速查找算法应用实例
2014/09/26 Python
Python中的ctime()方法使用教程
2015/05/22 Python
详细介绍Python的鸭子类型
2016/09/12 Python
python队列queue模块详解
2018/04/27 Python
解决Mac安装scrapy失败的问题
2018/06/13 Python
Python多线程同步---文件读写控制方法
2019/02/12 Python
python实现的自动发送消息功能详解
2019/08/15 Python
pytorch实现保证每次运行使用的随机数都相同
2020/02/20 Python
Python代码需要缩进吗
2020/07/01 Python
对Python 字典元素进行删除的方法
2020/07/31 Python
如何基于Django实现上下文章跳转
2020/09/16 Python
基于DOM+CSS3实现OrgChart组织结构图插件
2016/03/02 HTML / CSS
NUK奶瓶美国官网:NUK美国
2016/09/26 全球购物
快递业务员岗位职责
2014/01/06 职场文书
调解协议书
2014/04/16 职场文书
基本公共卫生服务健康教育工作方案
2014/05/22 职场文书
基层党建工作宣传标语
2014/06/24 职场文书
群众路线教育实践活动整改落实情况汇报
2014/10/28 职场文书
2015年银行个人工作总结
2015/05/14 职场文书