Python 遠程呼叫指令碼之 RPC

來源:互聯網
上載者:User

標籤:

最近有個監控需求,需要遠程執行叢集每個節點上的指令碼,並擷取指令碼執行結果,為了安全起見不需要帳號密碼登陸主機,要求只需要調用遠程指令碼模組的方法就能實現。

總結下python進行遠程呼叫指令碼方法:

  • 登陸主機執行指令碼,python模組支援如 pssh、pexpect、paramiko

  • 以遠程方法調用(不需要登陸主機),python模組 rpyc,支援分布式

  • socket 方式,稍顯複雜,需要熟悉網路通訊協定,起點比較高

rpyc支援遠程調用、分散式運算,以較少代碼量實現需複雜socket編程,本文主要介紹 rpyc 並用它來實現一個 demo。

以代碼方式介紹:

需求:分別執行叢集每個節點上 server 端的指令碼,並返回執行結果給 client 端

#Monitor_RPC_Client.py...hostDict = {‘*.*.*.189‘: 12345, ‘*.*.*..188‘: 12345, ‘*.*.*..187‘: 12345}class ProcessWorker(Thread):    def __init__(self, queue):        Thread.__init__(self)        self.queue = queue    def run(self):        while True:            host, port, localPath = self.queue.get()            try:                c = rpyc.connect(host, port)                localFileSize = c.root.getLocalFileSize(localPath, glob30minAgo)                localFileSizeDict[host] = localFileSize                c.close()            except Exception, e:                print ‘{0} → {1}:{2} occur a Error:{3}\n‘.format(self.getName(), host, port, e)def getLocalSize(localPath):    queue = Queue()    for x in range(3):        worker = ProcessWorker(queue)        worker.daemon = True        worker.start()    for (host, port) in hostDict.items():        queue.put((host, port, localPath))    time.sleep(3)    # queue.join()...#Monitor_RPC_Server.py...datePattern = re.compile(r‘\d{4}(?:-\d{2}){4}‘)def get_ip_address(ifname):    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)    return socket.inet_ntoa(fcntl.ioctl(        s.fileno(),        0x8915,  # SIOCGIFADDR        struct.pack(‘256s‘, ifname[:15])    )[20:24])class remote_call_func(Service):    def on_connect(self):        print "[{0}]\t--------------<<< on_connect".format(getNowTime())    def on_disconnect(self):        print "[{0}]\t-------------->>> on_disconnect".format(getNowTime())    def exposed_getLocalFileSize(self, path, glob30minAgo):        exitCode, execResult = commands.getstatusoutput("ls -lrt " + path + "`|awk ‘{s+=$5}END{print s}‘")        dateTime30minAgo = (datetime.datetime.now() - datetime.timedelta(minutes=30)).strftime("%Y-%m-%d %H:%M:%S")        print "[{0}] → {1} → {2}".format(dateTime30minAgo, path, format(execResult, ‘,‘))        return execResultrpycServer = ThreadedServer(remote_call_func, hostname=get_ip_address(‘eth0‘), port=12345, auto_register=False)rpycServer.start()

官方文檔中類似例子很多,就不詳細介紹了,需注意兩點:

  • server端定義方法需要被client調用,必須定義以exposed 開頭的方法,不然會報錯AttributeError: ‘remote_call_script’ object has no attribute ‘exposed_iamshell’

  • server端預設不設認證機制,如果需要認證有推薦兩種方法: ThreadedServer的authenticator參數與SSL模組

  • pip install rpyc ,如果 import rpyc 報錯則 yum install openssl-devel,然後重新編譯、安裝 python

當然還需要考慮很多異常處理,如逾時、驗證失敗等。

Refer:

[1] python遠程呼叫指令碼(一)

http://www.dbunix.com/?p=3262

http://rpyc.readthedocs.org/en/latest/tutorial.html

[2] python學習——python中執行shell命令

http://zhou123.blog.51cto.com/4355617/1312791

Python 遠程呼叫指令碼之 RPC

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.