python使用paramiko模块实现ssh远程登陆上传文件并执行
发布时间:2021-01-09 00:35:03
程序执行时需要读取两个文件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)


猜你喜欢
- 一、字符串的本质1.字符串的定义golang中的字符(character)串指的是所有8比特位字节字符串的集合,通常(非必须)是UTF-8&
- 一、了解FTP服务器FTP(文件传输协议),运行在tcp洗衣上,使用两个端口,即数据端口和命令端口,也称之为控制端口。默认情况下,20是数据
- 本文实例为大家分享了js实现五子棋游戏的具体代码,供大家参考,具体内容如下html:<body> <h2>五子棋游戏
- 也就在前几天,南太平洋岛国汤加发生火山喷发,有专门的专家学者分析,这可能是30年来全球规模最大的一次海底火山喷发,它引发的海啸以及火山灰将对
- 基本操作查看数据库<code>show databases;</code>指定字符集<code>crea
- 最近遇到一个问题,就是获取表单中的日期往后台通过json方式传的时候,遇到Date.parse(str)函数在ff下报错: NAN 找了些资
- 如下所示:#利用小波分析进行特征分析#参数初始化inputfile= 'C:/Users/Administrator/Desktop
- 本文实例讲述了Python闭包思想与用法。分享给大家供大家参考,具体如下:浅谈 python 的闭包思想首先 python的闭包使用方法是:
- 本文实例讲述了python 协程 gevent原理与用法。分享给大家供大家参考,具体如下:geventgreenlet已经实现了协程,但是这
- 网上的很多PHP微信支付接入教程都颇为复杂,且需要配置和引入较多的文件,本人通过整理后给出一个单文件版的,希望可以给各位想接入微信支付的带来
- 零、本讲学习目标了解面向对象编程思想掌握类和对象的定义和使用了解Python中的对象一、面向对象(一)程序员“面向对象”在现实世界中存在各种
- 1.前言我在进行DEM数据的裁剪时,发现各个省的数据量非常大,比如说四川省的30m的DEM数据的大小为2G。考虑到有限的电脑磁盘空间,我对T
- 前段时间前在网上看到一段面试题,要求如下:employee文件中记录了工号和姓名 cat employe
- 本文的OCR当然不是自己从头开发的,是基于百度智能云提供的API(我感觉是百度在中国的人工智能领域值得称赞的一大贡献),其提供的API完全可
- 做开发中难免时间类型之间的转换, 最近就发现前端js和后端django经常要用到这个转换, 其中jsDate.now()精确到毫秒,而Pyt
- 上篇关于Go模板库应用 的文章最后我们留下一个问题,页面模板是通过 CDN 引用的 BootStrap 的 css , js 文件。到目前位
- Window.Open详解 一、window.open()支持环境:JavaScript1.0+/JScript1.0+/Nav2
- python判断字符串的前两个字母是否是”id"你可以使用 Python 的字符串切片来判断一个字符串的前两个
- 前言昨天因为小程序功能要获取小程序程序码,看了微信文档爬了好多坑。(留一下记录以防后面被坑)操作因为我获取到了微信那里的图片的图片流一直不知
- 本文实例讲述了Python3.5常见内置方法参数用法。分享给大家供大家参考,具体如下:Python的内置方法参数详解网站为:https://