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登录QQ邮箱发信的实现代码
Feb 10 Python
python数据清洗系列之字符串处理详解
Feb 12 Python
Python语言描述连续子数组的最大和
Jan 04 Python
使用Python从零开始撸一个区块链
Mar 14 Python
Python Web编程之WSGI协议简介
Jul 18 Python
Python数据类型之Dict字典实例详解
May 07 Python
numpy.meshgrid()理解(小结)
Aug 01 Python
浅谈Django2.0 加xadmin踩的坑
Nov 15 Python
Python Django搭建网站流程图解
Jun 13 Python
通过实例了解python__slots__使用方法
Sep 14 Python
python 决策树算法的实现
Oct 09 Python
python 操作excel表格的方法
Dec 05 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 文件上传进度条的两种实现方法的代码
2007/11/25 PHP
PHP 魔术变量和魔术函数详解
2015/02/25 PHP
PHP进程通信基础之信号
2017/02/19 PHP
showModelessDialog()使用详解
2006/09/07 Javascript
Javascript模板技术
2007/04/27 Javascript
img的onload的另类用法
2008/01/10 Javascript
Javascript学习笔记-详解in运算符
2011/09/13 Javascript
Js中获取frames中的元素示例代码
2013/07/30 Javascript
JS控制阿拉伯数字转为中文大写示例代码
2013/09/04 Javascript
巧用replace将文字表情替换为图片
2014/04/17 Javascript
jQuery异步验证用户名是否存在示例代码
2014/05/21 Javascript
JavaScript实现仿网易通行证表单验证
2015/05/25 Javascript
Js+php实现异步拖拽上传文件
2015/06/23 Javascript
详解EasyUi控件中的Datagrid
2017/08/23 Javascript
vue的常用组件操作方法应用分析
2018/04/13 Javascript
vue弹窗组件使用方法
2018/04/28 Javascript
深入剖析Node.js cluster模块
2018/05/23 Javascript
基于vue2.0实现仿百度前端分页效果附实现代码
2018/10/30 Javascript
原生JS无缝滑动轮播图
2019/10/22 Javascript
[01:07:46]完美世界DOTA2联赛循环赛 Magma vs IO BO2第二场 11.01
2020/11/02 DOTA
详解在Python程序中使用Cookie的教程
2015/04/30 Python
python opencv实现图片旋转矩形分割
2018/07/26 Python
Python对切片命名的实现方法
2018/10/16 Python
Python装饰器基础概念与用法详解
2018/12/22 Python
Python根据当前日期取去年同星期日期
2019/04/14 Python
Python获取时间范围内日期列表和周列表的函数
2019/08/05 Python
python解析命令行参数的三种方法详解
2019/11/29 Python
解决PyCharm不在run输出运行结果而不是再Console里输出的问题
2020/09/21 Python
全球最大的游戏市场:G2A
2018/07/05 全球购物
十八届三中全会报告学习材料
2014/02/17 职场文书
会议主持人开场白台词
2015/05/28 职场文书
让世界充满爱观后感
2015/06/10 职场文书
python 模块重载的五种方法
2021/04/24 Python
Python列表删除重复元素与图像相似度判断及删除实例代码
2021/05/07 Python
Vue全局事件总线你了解吗
2022/02/24 Vue.js
5个pandas调用函数的方法让数据处理更加灵活自如
2022/04/24 Python