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实现的多线程端口扫描工具分享
Jan 21 Python
Python中为什么要用self探讨
Apr 14 Python
Python自动登录126邮箱的方法
Jul 10 Python
python数据结构链表之单向链表(实例讲解)
Jul 25 Python
Python使用回溯法子集树模板获取最长公共子序列(LCS)的方法
Sep 08 Python
Python3结合Dlib实现人脸识别和剪切
Jan 24 Python
python微信跳一跳系列之棋子定位颜色识别
Feb 26 Python
简单了解python元组tuple相关原理
Dec 02 Python
Django与pyecharts结合的实例代码
May 13 Python
python字典的值可以修改吗
Jun 29 Python
浅谈django不使用restframework自定义接口与使用的区别
Jul 15 Python
使用Python将xmind脑图转成excel用例的实现代码(一)
Oct 12 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/11/22 PHP
PHP session有效期session.gc_maxlifetime
2011/04/20 PHP
php使用filter过滤器验证邮箱 ipv6地址 url验证
2013/12/25 PHP
浅谈PHP变量作用域以及地址引用问题
2013/12/27 PHP
php对数组内元素进行随机调换的方法
2015/05/12 PHP
PHP正则获取页面所有图片地址
2016/03/23 PHP
php中get_magic_quotes_gpc()函数说明
2017/02/06 PHP
利用PHP_XLSXWriter代替PHPExcel的方法示例
2017/07/16 PHP
phpstudy的php版本自由修改的方法
2017/10/18 PHP
PHP实现的CURL非阻塞调用类
2018/07/26 PHP
PHP实现简单的协程任务调度demo示例
2020/02/01 PHP
jQuery使用手册之一
2007/03/24 Javascript
javascript Array.remove() 数组删除
2009/08/06 Javascript
原生js操作checkbox用document.getElementById实现
2013/10/12 Javascript
关闭浏览器窗口弹出提示框并且可以控制其失效
2014/04/15 Javascript
基于jquery实现人物头像跟随鼠标转动
2015/08/23 Javascript
收藏AngularJS中最重要的核心功能
2017/07/09 Javascript
用Vue-cli搭建的项目中引入css报错的原因分析
2017/07/20 Javascript
jQuery实现为动态添加的元素绑定事件实例分析
2018/09/07 jQuery
JS实现公告上线滚动效果
2021/01/10 Javascript
import的本质解析
2017/10/30 Python
python opencv之SURF算法示例
2018/02/24 Python
Python不使用int()函数把字符串转换为数字的方法
2018/07/09 Python
详解Django的CSRF认证实现
2018/10/09 Python
使用python 写一个静态服务(实战)
2019/06/28 Python
Django --Xadmin 判断登录者身份实例
2020/07/03 Python
Python设计密码强度校验程序
2020/07/30 Python
多个版本的python共存时使用pip的正确做法
2020/10/26 Python
高一课前三分钟演讲稿
2014/09/13 职场文书
婚礼父母答谢词
2015/01/04 职场文书
现场施工员岗位职责
2015/04/11 职场文书
高考诚信考试承诺书
2015/04/29 职场文书
博物馆观后感
2015/06/05 职场文书
公司出差管理制度范本
2015/08/05 职场文书
小学班主任研修日志
2015/11/13 职场文书
Python 多线程之threading 模块的使用
2021/04/14 Python