python使用paramiko模組實現ssh遠程登陸上傳檔案並執行

來源:互聯網
上載者:User
程式執行時需要讀取兩個檔案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

程式中的隊列操作是修改的別的程式,寫的確實不錯。
該程式亦正亦邪,如果拿去做壞事,我先聲明與我無關,我只是分享My Code罷了。
希望有興趣的同志們來討論技術應用。
這其中用到了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)

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.