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 相关文章推荐
2款Python内存检测工具介绍和使用方法
Jun 01 Python
Python编程实现数学运算求一元二次方程的实根算法示例
Apr 02 Python
python 执行shell命令并将结果保存的实例
May 11 Python
python web框架Flask实现图形验证码及验证码的动态刷新实例
Oct 14 Python
python Pillow图像处理方法汇总
Oct 16 Python
python被修饰的函数消失问题解决(基于wraps函数)
Nov 04 Python
Python3.7+tkinter实现查询界面功能
Dec 24 Python
Python中import导入不同目录的模块方法详解
Feb 18 Python
Django ORM filter() 的运用详解
May 14 Python
python如何利用paramiko执行服务器命令
Nov 07 Python
python regex库实例用法总结
Jan 03 Python
判断Python中的Nonetype类型
May 25 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异常处理浅析
2015/05/12 PHP
PHP获取二维数组中某一列的值集合
2015/12/25 PHP
php中使用GD库做验证码
2016/03/31 PHP
Zend Framework入门教程之Zend_Session会话操作详解
2016/12/08 PHP
jquery表格内容筛选实现思路及代码
2013/04/16 Javascript
jquery ajax同步异步的执行最终解决方案
2013/04/26 Javascript
jquery实现按Enter键触发事件示例
2013/09/10 Javascript
JS截取字符串常用方法详细整理
2013/10/28 Javascript
input链接页面、打开新网页等等的具体实现
2013/12/30 Javascript
jquery实现图片左右切换的方法
2015/05/07 Javascript
jquery简单倒计时实现方法
2015/12/18 Javascript
基于Javascript实现倒计时功能
2016/02/22 Javascript
AngularJS 与Bootstrap实现表格分页实例代码
2016/10/14 Javascript
详解获取jq ul第一个li定位的四种解决方案
2016/11/23 Javascript
Jqprint实现页面打印
2017/01/06 Javascript
Vue Cli与BootStrap结合实现表格分页功能
2017/08/18 Javascript
jQuery 导航自动跟随滚动的实现代码
2018/05/30 jQuery
Vue唯一可以更改vuex实例中state数据状态的属性对象Mutation的讲解
2019/01/18 Javascript
详解Vue+Element的动态表单,动态表格(后端发送配置,前端动态生成)
2019/04/20 Javascript
JavaScript实现页面中录音功能的方法
2019/06/04 Javascript
vue 中固定导航栏的实例代码
2019/11/01 Javascript
[01:06:59]完美世界DOTA2联赛PWL S2 Magma vs FTD 第一场 11.29
2020/12/02 DOTA
python中from module import * 的一个坑
2014/07/20 Python
Python输出汉字字库及将文字转换为图片的方法
2016/06/04 Python
详解pandas.DataFrame中删除包涵特定字符串所在的行
2019/04/04 Python
使用python脚本自动创建pip.ini配置文件代码实例
2019/09/20 Python
HTML5 直播疯狂点赞动画实现代码 附源码
2020/04/14 HTML / CSS
YSL Beauty加拿大官方商城:圣罗兰美妆加拿大
2017/05/15 全球购物
美国领先的奢侈美容零售商:Bluemercury
2017/07/26 全球购物
英国最大的在线床超市:Bed Star
2019/01/24 全球购物
屈臣氏越南官网:Watsons越南
2021/01/14 全球购物
五年级音乐教学反思
2014/02/06 职场文书
《兰亭集序》教学反思
2014/02/11 职场文书
王力宏牛津大学演讲稿
2014/05/22 职场文书
2015年村计划生育工作总结
2015/04/28 职场文书
2015年计算机教学工作总结
2015/07/22 职场文书