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 21 Python
浅析Python的Django框架中的Memcached
Jul 23 Python
python的构建工具setup.py的方法使用示例
Oct 23 Python
Python发送http请求解析返回json的实例
Mar 26 Python
利用python实现在微信群刷屏的方法
Feb 21 Python
Python实现的排列组合、破解密码算法示例
Apr 12 Python
Python、 Pycharm、Django安装详细教程(图文)
Apr 12 Python
浅谈Pycharm的项目文件名是红色的原因及解决方式
Jun 01 Python
在终端启动Python时报错的解决方案
Nov 20 Python
如何用Python提取10000份log中的产品信息
Jan 14 Python
python 机器学习的标准化、归一化、正则化、离散化和白化
Apr 16 Python
Python中zipfile压缩包模块的使用
May 14 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
Linux下进行MYSQL编程时插入中文乱码的解决方案
2007/03/15 PHP
PHP设计模式 注册表模式(多个类的注册)
2012/02/05 PHP
PHP导出EXCEL快速开发指南--PHPEXCEL的使用详解
2013/06/03 PHP
PHP可变函数的使用详解
2013/06/14 PHP
Laravel框架路由配置总结、设置技巧大全
2014/09/03 PHP
php采集内容中带有图片地址的远程图片并保存的方法
2015/01/03 PHP
php操作MongoDB类实例
2015/06/17 PHP
PHP7+Nginx的配置与安装教程详解
2016/05/10 PHP
js打印纸函数代码(递归)
2010/06/18 Javascript
js 字符串转化成数字的代码
2011/06/29 Javascript
基于JavaScript 下namespace 功能的简单分析
2013/07/05 Javascript
JS 有趣的eval优化输入验证实例代码
2013/09/22 Javascript
js中小数转换整数的方法
2014/01/26 Javascript
JS提交form表单实例分析
2015/12/10 Javascript
原生JS和jQuery操作DOM对比总结
2017/01/19 Javascript
微信小程序使用audio组件播放音乐功能示例【附源码下载】
2017/12/08 Javascript
vue-cli 默认路由再子路由选中下的选中状态问题及解决代码
2018/09/06 Javascript
浅谈Webpack核心模块tapable解析
2018/09/11 Javascript
vue给对象动态添加属性和值的实例
2019/09/09 Javascript
vue项目中使用rem,在入口文件添加内容操作
2020/11/11 Javascript
python 调用win32pai 操作cmd的方法
2017/05/28 Python
Python采集代理ip并判断是否可用和定时更新的方法
2018/05/07 Python
python 中pyqt5 树节点点击实现多窗口切换问题
2019/07/04 Python
pip install python 快速安装模块的教程图解
2019/10/08 Python
Pycharm+Python工程,引用子模块的实现
2020/03/09 Python
TensorFlow tf.nn.conv2d_transpose是怎样实现反卷积的
2020/04/20 Python
python文件及目录操作代码汇总
2020/07/08 Python
pytorch下的unsqueeze和squeeze的用法说明
2021/02/06 Python
使用HTML5的Notification API制作web通知的教程
2015/05/08 HTML / CSS
服务员自我评价
2014/01/25 职场文书
母亲节感恩寄语
2014/02/21 职场文书
单位委托书范本(3篇)
2014/09/18 职场文书
置业顾问岗位职责
2015/02/09 职场文书
求职自荐信范文(优秀篇)
2015/03/27 职场文书
解决pycharm下载库时出现Failed to install package的问题
2021/09/04 Python
python入门学习关于for else的特殊特性讲解
2021/11/20 Python