使用python編寫的簡單遠程管理軟件


因為用戶可以選擇是否同意被控制,所以並不算是木馬。

使用python3.7,spyder,在windows 10 開發。

client為控制端,server為被控端。

 

參考 mygithub https://github.com/TouwaErioH/simple-trojan

server.py

 

# -*- coding: utf-8 -*-
"""
Created on Sun Jun 23 19:33:37 2019
@author: frame by SmallBillows(GWT)  function by erio(LQ)
"""

import wx
import os
import numpy as np
from PIL import ImageGrab 
import socket
import sys
import struct
import cv2
import pyaudio
import wave

HOST = '127.0.0.1'
PORT = 51327
input_filenamescr = "screen.jpg"                         
input_filepath = "E:"          
in_pathscr = input_filepath + input_filenamescr  
input_filename = "record.wav"                          # 麥克風采集的語音輸入
input_filepath = "E:"              # 輸入文件的path
in_pathrec = input_filepath + input_filename  
input_filenamecam = "camera.jpg"                         
input_filepath = "E:"          
in_pathcam = input_filepath + input_filenamecam   



def get_screen(filepatha):    #攝像頭截圖
       img = ImageGrab.grab()
       img.save(filepatha)


def get_audio(filepath):  #麥克風錄音
        CHUNK = 256                 #定義數據流塊
        FORMAT = pyaudio.paInt16    #量化位數(音量級划分)
        CHANNELS = 1               # 聲道數;聲道數:可以是單聲道或者是雙聲道
        RATE = 8000                # 采樣率;采樣率:一秒內對聲音信號的采集次數,常用的有8kHz, 16kHz, 32kHz, 48kHz, 11.025kHz, 22.05kHz, 44.1kHz
        RECORD_SECONDS = 10          #錄音秒數
        WAVE_OUTPUT_FILENAME = filepath     #wav文件路徑
        p = pyaudio.PyAudio()               #實例化

        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK)
       # print("*"*10, "開始錄音:請在5秒內輸入語音")
        frames = []                                                 #定義一個列表
        for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):      #循環,采樣率11025 / 256 * 5
            data = stream.read(CHUNK)                               #讀取chunk個字節 保存到data中
            frames.append(data)                                     #向列表frames中添加數據data
      #  print(frames)
      #  print("*" * 10, "錄音結束\n")

        stream.stop_stream()
        stream.close()          #關閉
        p.terminate()           #終結

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')                  #打開wav文件創建一個音頻對象wf,開始寫WAV文件
        wf.setnchannels(CHANNELS)                                   #配置聲道數
        wf.setsampwidth(p.get_sample_size(FORMAT))                  #配置量化位數
        wf.setframerate(RATE)                                       #配置采樣率
        wf.writeframes(b''.join(frames))                            #轉換為二進制數據寫入文件
        wf.close()              #關閉
        
#拍照
 
def get_camera(filepath):
   cap=cv2.VideoCapture(0)
   ret,frame = cap.read()
   i=0;
   cv2.imwrite(filepath,frame)
   cap.release()
   cv2.destroyAllWindows()        


class MainWindow(wx.Frame):
    def __init__(self,parent,title):
        self.dirname = ''
        wx.Frame.__init__(self,parent,title=title,size=(200,-1))
        self.contrl = wx.Frame() #暫時不用這個控件
        self.CreateStatusBar()# 創建位於窗口的底部的狀態欄

        #設置菜單
        filemenu = wx.Menu()

        menuOpen = filemenu.Append(wx.ID_OPEN,"&Open","Open a file")
        menuAbout = filemenu.Append(wx.ID_ABOUT,"&About","Information about this program") #(ID, 項目名稱, 狀態欄信息)
        filemenu.AppendSeparator()  #分割線
        menuExit = filemenu.Append(wx.ID_EXIT,"&Exit","Terminate the program") # (ID, 項目名稱, 狀態欄信息)


        #創建菜單欄
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu, "&File") #在菜單欄中添加filemenu菜單
        self.SetMenuBar(menuBar) #在frame中添加菜單欄

        #設置 events
        self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
        self.Bind(wx.EVT_MENU, self.OnAbout,menuAbout)
        self.Bind(wx.EVT_MENU, self.OnExit,menuExit)

        #設置 sizer
        self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        self.buttons = []
        self.buttons.append(wx.Button(self, -1, "開啟服務器"))
        self.sizer2.Add(self.buttons[0], 1, wx.SHAPED)
        self.buttons.append(wx.Button(self, -1, "quit"))
        self.sizer2.Add(self.buttons[1], 1, wx.SHAPED)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.contrl,1,wx.EXPAND)
        self.sizer.Add(self.sizer2,0,wx.GROW)
        
        self.Bind(wx.EVT_BUTTON, self.OpenServer, self.buttons[0])
        self.Bind(wx.EVT_BUTTON, self.Quit, self.buttons[1])

        #激活sizer
        self.SetSizer(self.sizer)
        self.SetAutoLayout(True)
        self.sizer.Fit(self)
        self.Show(True)
        
        
    def OpenServer(self,e):
            s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
            print('waiting ------->')
            s.connect((HOST,PORT))       
            dlg = wx.MessageDialog(None, "connected with:"+HOST+"對方將控制你的機器", "Check", wx.YES_NO)
            if dlg.ShowModal() == wx.ID_NO:
                    trigger = '0'
                    s.sendall(trigger.encode())
                    dlg = wx.MessageDialog(self,'拒絕被控制',"Connection",wx.OK)
                    dlg.ShowModal() #顯示對話框
                    dlg.Destroy()   #當結束之后關閉對話框
                    self.Close(True)
            else:
                 dlg = wx.MessageDialog(self,'同意被控制',"Connection",wx.OK)
                 dlg.ShowModal() #顯示對話框
                 dlg.Destroy()   #當結束之后關閉對話框
                 trigger = '1'
                 s.sendall(trigger.encode())
            while True:
             data = s.recv(1024)
             data = data.decode()
             if data.lower() == '1':
               print('對方將獲取你的屏幕截圖')
               get_screen(in_pathscr)
               filepath = in_pathscr
               if os.path.isfile(filepath):
                   fileinfo_size = struct.calcsize('128sl')
                   fhead = struct.pack('128sl', bytes(os.path.basename(filepath).encode()),os.stat(filepath).st_size)  #encode很重要
                   s.send(fhead)
                   print ('client filepath: {0}'.format(filepath))  #
                   fp = open(filepath, 'rb')  # rb 以二進制格式打開一個文件用於讀寫。文件指針將會放在文件的開頭。
                   while 1:
                       data = fp.read(1024)
                       if not data:
                           print ('{0} file send over...'.format(filepath))
                           break
                       s.send(data)
             elif data.lower() == '2':
                   print('對方將獲取你的錄音')
                   get_audio(in_pathrec)
                   filepath = in_pathrec
                   if os.path.isfile(filepath):
                       fileinfo_size = struct.calcsize('128sl')
                       fhead = struct.pack('128sl', bytes(os.path.basename(filepath).encode()),os.stat(filepath).st_size)  #encode很重要
                       s.send(fhead)
                       print ('client filepath: {0}'.format(filepath))  #
                       fp = open(filepath, 'rb')  # rb 以二進制格式打開一個文件用於讀寫。文件指針將會放在文件的開頭。
                       while 1:
                           data = fp.read(1024)
                           if not data:
                               print ('{0} file send over...'.format(filepath))
                               break
                           s.send(data)    
             elif data.lower() == '3':
                   print('對方將獲取你的攝像頭拍照')
                   get_camera(in_pathcam)
                   filepath = in_pathcam
                   if os.path.isfile(filepath):
                       fileinfo_size = struct.calcsize('128sl')
                       fhead = struct.pack('128sl', bytes(os.path.basename(filepath).encode()),os.stat(filepath).st_size)  #encode很重要
                       s.send(fhead)
                       print ('client filepath: {0}'.format(filepath))  #
                       fp = open(filepath, 'rb')  # rb 以二進制格式打開一個文件用於讀寫。文件指針將會放在文件的開頭。
                       while 1:
                           data = fp.read(1024)
                           if not data:
                               print ('{0} file send over...'.format(filepath))
                               break
                           s.send(data) 
             elif data.lower() == '4':
                 fileinfo_size=struct.calcsize('128sl')
                 buf = s.recv(fileinfo_size)
                 if buf:
                     filename, filesize = struct.unpack('128sl', buf)
                     fn = filename.decode().strip('\00')                             #Python strip() 方法用於刪除字符串頭部和尾部指定的字符,默認字符為所有空字符,包括空格、換行(\n)、制表符(\t)等。
                     new_filename = os.path.join('./', 'new_' + fn)
                     print ('file new name is {0}, filesize is {1}'.format(new_filename,
                                                                     filesize))
                     
                     recvd_size = 0  # 定義已接收文件的大小
                     dlg = wx.MessageDialog(self,'在server路徑下收到文件'+new_filename,"Connection",wx.OK)
                     dlg.ShowModal() #顯示對話框
                     dlg.Destroy()   #當結束之后關閉對話框
                     fp = open(new_filename, 'wb')
                     print ('start receiving...')
                     
                     while not recvd_size == filesize:
                         if filesize - recvd_size > 1024:
                             data = s.recv(1024)
                             recvd_size += len(data)
                         else:
                                 data = s.recv(filesize - recvd_size)
                                 recvd_size = filesize
                         fp.write(data)
                     fp.close()
                     print ('end receive...')
             elif data.lower() == '5':
                   print('對方將獲取你的E:jojo.txt') #這里應該先接收路徑,處理后將該文件發給client
                   filepath = 'E:jojo.txt'   #簡單點,發送E:jojo.txt
                   if os.path.isfile(filepath):
                       fileinfo_size = struct.calcsize('128sl')
                       fhead = struct.pack('128sl', bytes(os.path.basename(filepath).encode()),os.stat(filepath).st_size)  #encode很重要
                       s.send(fhead)
                       print ('client filepath: {0}'.format(filepath))  #
                       fp = open(filepath, 'rb')  # rb 以二進制格式打開一個文件用於讀寫。文件指針將會放在文件的開頭。
                       while 1:
                           data = fp.read(1024)
                           if not data:
                               print ('{0} file send over...'.format(filepath))
                               break
                           s.send(data) 
             elif data.lower() == '-1':
                  s.close()
                  self.Close(True)
                   
            

    def Quit(self,e):
        self.Close(True)
        
    def OnAbout(self,e):
        #創建一個帶"OK"按鈕的對話框。wx.OK是wxWidgets提供的標准ID
        dlg = wx.MessageDialog(self,"小組成員:劉Q 郭WT","About Editors",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()   #當結束之后關閉對話框

    def OnExit(self,e):
        self.Close(True)  #關閉整個frame

    def OnOpen(self,e):
        dlg = wx.FileDialog(self,"Choose a file",self.dirname,"","*·*",wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            f = open(os.path.join(self.dirname,self.filename),'r')#暫時只讀
            self.contrl.SetValue(f.read())
            f.colse()
        dlg.Destroy()
        
if __name__ == '__main__':
    
    app = wx.App(False)
    frame = MainWindow(None,title="Server")
    app.MainLoop()
    
            
            

 

client.py

# -*- coding: utf-8 -*-
"""
Created on Sun Jun 23 19:33:37 2019

@author: frame by SmallBillows(GWT)  function by erio(LQ)
"""

import wx
import os
import numpy as np
import time
from PIL import ImageGrab 
import socket
import sys
import struct

HOST = '127.0.0.1'
PORT = 51327
func='-1'

class MainWindow(wx.Frame):
    def __init__(self,parent,title):
        self.dirname = ''
        wx.Frame.__init__(self,parent,title=title,size=(200,-1))
        self.contrl = wx.Frame() #暫時不用這個控件
        self.CreateStatusBar()# 創建位於窗口的底部的狀態欄

        #設置菜單
        filemenu = wx.Menu()

        menuOpen = filemenu.Append(wx.ID_OPEN,"&Open","Open a file")
        menuAbout = filemenu.Append(wx.ID_ABOUT,"&About","Information about this program") #(ID, 項目名稱, 狀態欄信息)
        filemenu.AppendSeparator()  #分割線
        menuExit = filemenu.Append(wx.ID_EXIT,"&Exit","Terminate the program") # (ID, 項目名稱, 狀態欄信息)


        #創建菜單欄
        menuBar = wx.MenuBar()
        menuBar.Append(filemenu, "&File") #在菜單欄中添加filemenu菜單
        self.SetMenuBar(menuBar) #在frame中添加菜單欄

        #設置 events
        self.Bind(wx.EVT_MENU, self.OnOpen, menuOpen)
        self.Bind(wx.EVT_MENU, self.OnAbout,menuAbout)
        self.Bind(wx.EVT_MENU, self.OnExit,menuExit)

        #設置 sizer
        self.sizer2 = wx.BoxSizer(wx.HORIZONTAL)
        self.buttons = []
        self.buttons.append(wx.Button(self, -1, "文件瀏覽"))
        self.sizer2.Add(self.buttons[0], 1, wx.SHAPED)
        self.buttons.append(wx.Button(self, -1, "文件上傳"))
        self.sizer2.Add(self.buttons[1], 1, wx.SHAPED)
        self.buttons.append(wx.Button(self, -1, "文件下載"))
        self.sizer2.Add(self.buttons[2], 1, wx.SHAPED)
        self.buttons.append(wx.Button(self, -1, "文件執行"))
        self.sizer2.Add(self.buttons[3], 1, wx.SHAPED)
        self.buttons.append(wx.Button(self, -1, "開啟攝像頭"))
        self.sizer2.Add(self.buttons[4], 1, wx.SHAPED)
        self.buttons.append(wx.Button(self, -1, "開啟麥克風"))
        self.sizer2.Add(self.buttons[5], 1, wx.SHAPED)
        self.buttons.append(wx.Button(self, -1, "OpenClient"))
        self.sizer2.Add(self.buttons[6], 1, wx.SHAPED)
        self.buttons.append(wx.Button(self, -1, "屏幕截屏"))
        self.sizer2.Add(self.buttons[7], 1, wx.SHAPED)
        self.buttons.append(wx.Button(self, -1, "quit"))
        self.sizer2.Add(self.buttons[8], 1, wx.SHAPED)
        self.sizer = wx.BoxSizer(wx.VERTICAL)
        self.sizer.Add(self.contrl,1,wx.EXPAND)
        self.sizer.Add(self.sizer2,0,wx.GROW)
        
        self.Bind(wx.EVT_BUTTON, self.Fileview, self.buttons[0])
        self.Bind(wx.EVT_BUTTON, self.FileUpload, self.buttons[1])
        self.Bind(wx.EVT_BUTTON, self.FileDownload, self.buttons[2])
        self.Bind(wx.EVT_BUTTON, self.FileExecute, self.buttons[3])
        self.Bind(wx.EVT_BUTTON, self.OpenCamera, self.buttons[4])
        self.Bind(wx.EVT_BUTTON, self.OpenMicrophone, self.buttons[5])
        self.Bind(wx.EVT_BUTTON, self.OpenClient, self.buttons[6])
        self.Bind(wx.EVT_BUTTON, self.ScreenView, self.buttons[7])
        self.Bind(wx.EVT_BUTTON, self.Quit, self.buttons[8])

        #激活sizer
        self.SetSizer(self.sizer)
        self.SetAutoLayout(True)
        self.sizer.Fit(self)
        self.Show(True)
        
        
        
        
        
    def Fileview(self,e):
        
        dlg = wx.MessageDialog(self,"使用簡單的遍歷就可以獲取路徑,思路簡單。但是我想要做成圖形化的顯示,時間所限暫時未完成","Fileview",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()
        
    def FileUpload(self,e):
        func='4'
        dlg = wx.MessageDialog(self,"將上傳指定文件到server路徑下","FileUpload",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()
        #print('將上傳指定文件到server路徑下')
        send = func
        conn.sendall(send.encode())
        '''
        path_text = wx.TextCtrl(frame, pos=(5, 5), size=(350, 24))
        print(path_text)
        這里可以用textctrl獲取想要上傳的文件的路徑。
        方便起見,我們先上傳固定路徑的某個文件
        '''
        filepath = 'E:test.txt'
        if os.path.isfile(filepath):
                   fileinfo_size = struct.calcsize('128sl')
                   fhead = struct.pack('128sl', bytes(os.path.basename(filepath).encode()),os.stat(filepath).st_size)  #encode很重要
                   conn.send(fhead)
                   print ('client filepath: {0}'.format(filepath))  #
                   fp = open(filepath, 'rb')  # rb 以二進制格式打開一個文件用於讀寫。文件指針將會放在文件的開頭。
                   while 1:
                       data = fp.read(1024)
                       if not data:
                           print ('{0} file send over...'.format(filepath))
                           break
                       conn.send(data)
        dlg = wx.MessageDialog(self,"Upload E:test.txt","FileUpload",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()
        
    def FileDownload(self,e):
        func='5'
        dlg = wx.MessageDialog(self,"將下載指定文件到client路徑下","FileDownload",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()
       # print('將下載指定文件到client路徑下')
        send = func                            #這里應該輸入fileview獲取的server某個文件的路徑,傳送到server,server將該文件傳送過來
        conn.sendall(send.encode())
        fileinfo_size=struct.calcsize('128sl')   #簡單點,只下載server E:jojo.txt
        buf = conn.recv(fileinfo_size)
        if buf:
            filename, filesize = struct.unpack('128sl', buf)
            fn = filename.decode().strip('\00')                             #Python strip() 方法用於刪除字符串頭部和尾部指定的字符,默認字符為所有空字符,包括空格、換行(\n)、制表符(\t)等。
            new_filename = os.path.join('./', 'new_' + fn)
            print ('file new name is {0}, filesize is {1}'.format(new_filename,
                                                                 filesize))

            recvd_size = 0  # 定義已接收文件的大小
            fp = open(new_filename, 'wb')
            print ('start receiving...')

            while not recvd_size == filesize:
                if filesize - recvd_size > 1024:
                    data = conn.recv(1024)
                    recvd_size += len(data)
                else:
                    data = conn.recv(filesize - recvd_size)
                    recvd_size = filesize
                fp.write(data)
            fp.close()
            print ('end receive...')
        
        dlg = wx.MessageDialog(self,"Download E:jojo.txt from server to client's path!","FileDownload",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()
        
    def FileExecute(self,e):
        
        dlg = wx.MessageDialog(self,"使用os.system轉換路徑,然后執行文件。時間所限暫時未完成","FileExecute",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()
    
    def OpenCamera(self,e):
        func='3'
        print('將獲取被控制端的攝像頭拍照')
        send = func
        conn.sendall(send.encode())
        fileinfo_size=struct.calcsize('128sl')
        buf = conn.recv(fileinfo_size)
        if buf:
            filename, filesize = struct.unpack('128sl', buf)
            fn = filename.decode().strip('\00')                             #Python strip() 方法用於刪除字符串頭部和尾部指定的字符,默認字符為所有空字符,包括空格、換行(\n)、制表符(\t)等。
            new_filename = os.path.join('./', 'new_' + fn)
            print ('file new name is {0}, filesize is {1}'.format(new_filename,
                                                                 filesize))

            recvd_size = 0  # 定義已接收文件的大小
            fp = open(new_filename, 'wb')
            print ('start receiving...')

            while not recvd_size == filesize:
                if filesize - recvd_size > 1024:
                    data = conn.recv(1024)
                    recvd_size += len(data)
                else:
                    data = conn.recv(filesize - recvd_size)
                    recvd_size = filesize
                fp.write(data)
            fp.close()
            print ('end receive...')
        dlg = wx.MessageDialog(self,"已經收到被控端攝像頭拍照文件","Camera",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()
       # frame2 = wx.Frame(None,-1,title='OpenCamera',size=(400,-1))
       # frame2.Show()
        
    def OpenMicrophone(self,e):
        func='2'
        print('將獲取被控制端的麥克風錄音')
        send = func
        conn.sendall(send.encode())
        fileinfo_size=struct.calcsize('128sl')
        buf = conn.recv(fileinfo_size)
        if buf:
            filename, filesize = struct.unpack('128sl', buf)
            fn = filename.decode().strip('\00')                             #Python strip() 方法用於刪除字符串頭部和尾部指定的字符,默認字符為所有空字符,包括空格、換行(\n)、制表符(\t)等。
            new_filename = os.path.join('./', 'new_' + fn)
            print ('file new name is {0}, filesize is {1}'.format(new_filename,
                                                                 filesize))

            recvd_size = 0  # 定義已接收文件的大小
            fp = open(new_filename, 'wb')
            print ('start receiving...')

            while not recvd_size == filesize:
                if filesize - recvd_size > 1024:
                    data = conn.recv(1024)
                    recvd_size += len(data)
                else:
                    data = conn.recv(filesize - recvd_size)
                    recvd_size = filesize
                fp.write(data)
            fp.close()
            print ('end receive...')
        dlg = wx.MessageDialog(self,"已經收到被控端錄音文件","Camera",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()
       # frame3 = wx.Frame(None,-1,title='OpenMicrophone',size=(400,-1))
       # frame3.Show()
        
    def OpenClient(self,e):
        global line
        line = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
        line.bind((HOST,PORT))
        line.listen(3)
        global conn,addr
        conn,addr=line.accept()
        '''
        dlg = wx.MessageDialog(self,addr,"Connected",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()   #當結束之后關閉對話框
        '''
        data = conn.recv(1024)
        data = data.decode() 
        if data=='0':
         dlg = wx.MessageDialog(self,'對方拒絕被控制,斷開連接',"Connection",wx.OK)
         dlg.ShowModal() #顯示對話框
         dlg.Destroy()   #當結束之后關閉對話框
        else:
         dlg = wx.MessageDialog(self,'對方同意被控制',"Connection",wx.OK)
         dlg.ShowModal() #顯示對話框
         dlg.Destroy()   #當結束之后關閉對話框
        
        
    def ScreenView(self,e):
        func='1'
        print('將獲取被控制端的屏幕截圖')
        send = func
        conn.sendall(send.encode())
        fileinfo_size=struct.calcsize('128sl')
        buf = conn.recv(fileinfo_size)
        if buf:
            filename, filesize = struct.unpack('128sl', buf)
            fn = filename.decode().strip('\00')                             #Python strip() 方法用於刪除字符串頭部和尾部指定的字符,默認字符為所有空字符,包括空格、換行(\n)、制表符(\t)等。
            new_filename = os.path.join('./', 'new_' + fn)
            print ('file new name is {0}, filesize is {1}'.format(new_filename,
                                                                 filesize))

            recvd_size = 0  # 定義已接收文件的大小
            fp = open(new_filename, 'wb')
            print ('start receiving...')

            while not recvd_size == filesize:
                if filesize - recvd_size > 1024:
                    data = conn.recv(1024)
                    recvd_size += len(data)
                else:
                    data = conn.recv(filesize - recvd_size)
                    recvd_size = filesize
                fp.write(data)
            fp.close()
            print ('end receive...')
        dlg = wx.MessageDialog(self,"已經收到被控端截屏文件","Camera",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()
        #frame4 = wx.Frame(None,-1,title='ScreenView',size=(400,-1))
        #frame4.Show()
    
    def Quit(self,e):
        func='-1'
        conn.sendall(func.encode())
        line.close()                 #initial 否則可能造成下次打開,用到的端口還在被占用
        self.Close(True)
        
    def OnAbout(self,e):
        #創建一個帶"OK"按鈕的對話框。wx.OK是wxWidgets提供的標准ID
        dlg = wx.MessageDialog(self,"小組成員:劉強 郭文濤","About Editors",wx.OK)
        dlg.ShowModal() #顯示對話框
        dlg.Destroy()   #當結束之后關閉對話框

    def OnExit(self,e):
        self.Close(True)  #關閉整個frame

    def OnOpen(self,e):
        dlg = wx.FileDialog(self,"Choose a file",self.dirname,"","*·*",wx.FD_OPEN)
        if dlg.ShowModal() == wx.ID_OK:
            self.filename = dlg.GetFilename()
            self.dirname = dlg.GetDirectory()
            f = open(os.path.join(self.dirname,self.filename),'r')#暫時只讀
            self.contrl.SetValue(f.read())
            f.colse()
        dlg.Destroy()
        
if __name__ == '__main__':
    
    app = wx.App(False)
    frame = MainWindow(None,title="Client")
    app.MainLoop()

 

functions.py

# -*- coding: utf-8 -*-
"""
Created on Mon Jun 24 14:47:35 2019

@author: erio
"""

from PIL import Image,ImageGrab
import cv2
import pyaudio
import wave



'''
#錄音
input_filename = "record.wav"                          # 麥克風采集的語音輸入
input_filepath = "E:"              # 輸入文件的path
in_pathrec = input_filepath + input_filename         #通俗解釋就是wav文件路徑

def get_audio(filepath):
        CHUNK = 256                 #定義數據流塊
        FORMAT = pyaudio.paInt16    #量化位數(音量級划分)
        CHANNELS = 1               # 聲道數;聲道數:可以是單聲道或者是雙聲道
        RATE = 8000                # 采樣率;采樣率:一秒內對聲音信號的采集次數,常用的有8kHz, 16kHz, 32kHz, 48kHz, 11.025kHz, 22.05kHz, 44.1kHz
        RECORD_SECONDS = 10          #錄音秒數
        WAVE_OUTPUT_FILENAME = filepath     #wav文件路徑
        p = pyaudio.PyAudio()               #實例化

        stream = p.open(format=FORMAT,
                        channels=CHANNELS,
                        rate=RATE,
                        input=True,
                        frames_per_buffer=CHUNK)
       # print("*"*10, "開始錄音:請在5秒內輸入語音")
        frames = []                                                 #定義一個列表
        for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):      #循環,采樣率11025 / 256 * 5
            data = stream.read(CHUNK)                               #讀取chunk個字節 保存到data中
            frames.append(data)                                     #向列表frames中添加數據data
      #  print(frames)
      #  print("*" * 10, "錄音結束\n")

        stream.stop_stream()
        stream.close()          #關閉
        p.terminate()           #終結

        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')                  #打開wav文件創建一個音頻對象wf,開始寫WAV文件
        wf.setnchannels(CHANNELS)                                   #配置聲道數
        wf.setsampwidth(p.get_sample_size(FORMAT))                  #配置量化位數
        wf.setframerate(RATE)                                       #配置采樣率
        wf.writeframes(b''.join(frames))                            #轉換為二進制數據寫入文件
        wf.close()              #關閉
        
get_audio(in_pathrec)
'''



#截屏
input_filenamescr = "screen.jpg"                         
input_filepath = "E:"          
in_pathscr = input_filepath + input_filenamescr      
def get_screen(filepath):
   img = ImageGrab.grab()
   img.save(filepath)

get_screen(in_pathscr)





'''
#拍照
input_filenamecam = "camera.jpg"                         
input_filepath = "E:"          
in_pathcam = input_filepath + input_filenamecam    
def get_camera(filepath):
   cap=cv2.VideoCapture(0)
   ret,frame = cap.read()
   i=0;
   cv2.imwrite(filepath,frame)
   cap.release()
   cv2.destroyAllWindows()
   
get_camera(in_pathcam)
'''



'''
#錄制視頻
cap = cv2.VideoCapture(0)#創建一個 VideoCapture 對象

flag = 1 #設置一個標志,用來輸出視頻信息
num = 1 #遞增,用來保存文件名
while(cap.isOpened()):#循環讀取每一幀
    ret_flag, Vshow = cap.read() #返回兩個參數,第一個是bool是否正常打開,第二個是照片數組,如果只設置一個則變成一個tumple包含bool和圖片
    cv2.imshow("Capture_Test",Vshow)  #窗口顯示,顯示名為 Capture_Test
    k = cv2.waitKey(1) & 0xFF #每幀數據延時 1ms,延時不能為 0,否則讀取的結果會是靜態幀
    if k == ord('s'):  #若檢測到按鍵 ‘s’,打印字符串
        cv2.imwrite("D:/pycharmthings/IMF/getpics/"+ str(num) + ".jpg", Vshow)
        print(cap.get(3)); #得到長寬
        print(cap.get(4));
        print("success to save"+str(num)+".jpg")
        print("-------------------------")
        num += 1
    elif k == ord('q'): #若檢測到按鍵 ‘q’,退出
        break
cap.release() #釋放攝像頭
cv2.destroyAllWindows()#刪除建立的全部窗口
'''

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM