Python多線程登錄遠端linux執行操作命令
阿新 • • 發佈:2018-04-03
Python多線程登錄遠端linux執行
什麽是進程?
進程,就是程序的一個運行狀態。
什麽是線程?
為什麽要使用線程?
線程,是進程內部的“執行單元”。
一個進程,可以包含多個線程,每個線程又可以執行不同的代碼。
即,通過多個線程,可以使一個進程同時執行多個功能!
前提安裝sshpass
解法1.
#!/usr/bin/python #-*- coding:utf-8 import threading import os def linux_ls1(): while True: cmd="sshpass -p '00000000' ssh [email protected] ls" ret=os.popen(cmd) print ret.read() break def linux_ls2(): while True: cmd="sshpass -p '00000000' ssh [email protected] ls" ret=os.popen(cmd) print ret.read() break t1=threading.Thread(target=linux_ls1) t2=threading.Thread(target=linux_ls2) t1.start() t2.start()
解法2.
#!/usr/bin/python #-*- coding:utf-8 import threading import os def linux_ls1(pwd,user,ip): while True: cmd="sshpass -p '%s' ssh %s@%s ls" %(pwd,user,ip) ret=os.popen(cmd) print ret.read() break def linux_ls2(pwd,user,ip): while True: cmd="sshpass -p '%s' ssh %s@%s ls" %(pwd,user,ip) ret=os.popen(cmd) print ret.read() break t1=threading.Thread(target=linux_ls1,args=("00000000","root","192.168.135.105")) t2=threading.Thread(target=linux_ls2,args=("00000000","root","192.168.135.108")) t1.start() t2.start()
解法3.
#-*- coding:utf-8 -*- import threading import os def my_work(pwd,user,ip): while True: cmd="sshpass -p '%s' ssh %s@%s ls" %(pwd,user,ip) ret=os.popen(cmd) print ret.read() break class MyThread(threading.Thread): def __init__(self, pwd,user,ip): threading.Thread.__init__(self) self.pwd=pwd self.user=user self.ip=ip #線程啟動後,會執行self.run()方法 def run(self): my_work(self.pwd, self.user, self.ip) # 創建新線程t1 t1 = MyThread("00000000", "root","192.168.135.105") t2 = MyThread("00000000", "root","192.168.135.108") t1.start() #啟動線程 t2.start() print "線程啟動完畢"
解法4.
#!/usr/bin/python # encoding=utf-8 # Filename: put_files_hdfs.py # 讓多條命令並發執行,如讓多條scp,ftp,hdfs上傳命令並發執行,提高程序運行效率 import os import threading def execCmd(cmd): try: os.system(cmd) except Exception, e: print '%s\t 運行失敗,失敗原因\r\n%s' % (cmd,e) if __name__ == '__main__': # 需要執行的命令列表 cmds = ['sshpass -p "00000000" ssh [email protected] ls','sshpass -p "00000000" ssh [email protected] ls',] #線程池 threads = [] for cmd in cmds: th = threading.Thread(target=execCmd, args=(cmd,)) th.start() threads.append(th) # 等待線程運行完畢 for th in threads: th.join()
Python多線程登錄遠端linux執行操作命令