xmpppy + google talk => Remote control

xmpppy + google talk => Remote control

收+發

下載參考代碼:echo.py

使用Python+xmpppy通過gtalk服務收發消息

  • 返回信息(robot send)

    cnx.send(xmpp.Message(str(msg.getFrom()), str(msg.getBody())))

執行command

  • import os

    os.system('ifconfig')
    os.system(str(msg.getBody()))

  • import subprocess 〖帶返回信息output〗

    proc = subprocess.Popen([cmd], stdout=subprocess.PIPE, shell=True)
    (out, err) = proc.communicate()
    注:〖shell=True, 這一行參數的結果,即可實現 識別帶參數的command〗

返回command結果

  • 基本思路
    subprocess.Popen + cnx.send

  • timeout(如ping命令,執行時間過長,即kill process)
    參考如下代碼Ref


        from subprocess import Popen, PIPE
        import signal

        class ProcessTimeout(Exception):
            pass

        def timeout_handler(signum, frame):
            raise ProcessTimeout

        def run_timeout(cmd, timeout=None):
            if timeout:
                signal.signal(signal.SIGALRM, timeout_handler)
                signal.alarm(timeout)
            # proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
            proc = Popen([cmd], stdout=PIPE, stderr=PIPE, shell=True)
            stdout = stderr = ''
            try:
                stdout, stderr = proc.communicate()
                signal.alarm(0)
            except ProcessTimeout:
                proc.kill()
                stdout = 'Calculation was taking too long, so I killed it dead.'
            del proc
            return (stdout, stderr)

        #**************************************
        cmd="ping -c4 baidu.com"
        (out,err) = run_timeout(cmd, 10)
        (out2,err2) = run_timeout(cmd, 2)

        print "program output:", out
        print "program output2:", out2
        #**************************************

最終代碼

            #! /usr/bin/env python
            # encoding=UTF-8
            import os
            import xmpp
            import time
            import subprocess
            from subprocess import Popen, PIPE                                             
            import signal

            #****timeout
            class ProcessTimeout(Exception):
                pass

            def timeout_handler(signum, frame):
                raise ProcessTimeout

            def run_timeout(cmd, timeout=None):
                if timeout:
                    signal.signal(signal.SIGALRM, timeout_handler)
                    signal.alarm(timeout)
                # proc = Popen(cmd, stdout=PIPE, stderr=PIPE)
                proc = Popen([cmd], stdout=PIPE, stderr=PIPE, shell=True) #", shell=True"識別帶參數
                stdout = stderr = ''
                try:
                    stdout, stderr = proc.communicate()
                    signal.alarm(0)
                except ProcessTimeout:
                    proc.kill()
                    stdout = 'Calculation was taking too long, so I killed it dead.'
                del proc
                return (stdout, stderr)
            #****

            # 消息回調函數
            def messageCB(cnx, msg):
                # # 顯示消息發送者和內容
                print "Sender: " + str(msg.getFrom())
                print "Content: " + str(msg.getBody())

                cnx.send(xmpp.Message(str(msg.getFrom()), 'Accepted'))
                text = msg.getBody()
                user = msg.getFrom()

                (out,err) = run_timeout(str(text), 10)
                print "program output:", out
                # # 將消息又返回給發送者
                cnx.send(xmpp.Message(str(msg.getFrom()), '\n' + out))

            if __name__ == '__main__':
                # 給實例的gtalk帳號和密碼
                login = 'user***'
                pwd = 'pwd***'
                # 創建client對象
                cnx = xmpp.Client('gmail.com', debug=[])
                # 連接到google的服務器
                # cnx.connect(server=('talk.google.com', 443))
                cnx.connect(server=('talk.google.com', 5223)) #HW from“打印”
                # 用戶身份認證
                cnx.auth(login, pwd, 'UDPonNAT')
                # 告訴gtalk服務器用戶已經上線
                cnx.sendInitPresence()
                # 設置消息回調函數
                cnx.RegisterHandler('message', messageCB)
                # 循環處理消息,如果網絡斷開則結束循環
                while True:
                    if cnx.Process(1) == None:
                        print 'Lost connection.'
                        break
                # 無用,方便windows命令窗口調試
                while True:
                    time.sleep(1)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章