Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
 
(연관된 글이 1개 있습니다.)
(시리즈 글이 9개 있습니다.)
Windows: 148. Windows - Raw Input의 Top level collection 의미
; https://www.sysnet.pe.kr/2/0/11612

.NET Framework: 788. RawInput을 이용한 키보드/마우스 입력 모니터링
; https://www.sysnet.pe.kr/2/0/11615

개발 환경 구성: 488. (User-mode 코드로 가상 USB 장치를 만들 수 있는) USB/IP PROJECT 소개
; https://www.sysnet.pe.kr/2/0/12213

개발 환경 구성: 490. C# - (Wireshark의) USBPcap을 이용한 USB 패킷 모니터링
; https://www.sysnet.pe.kr/2/0/12215

.NET Framework: 904. USB/IP PROJECT를 이용해 C#으로 USB Keyboard 가상 장치 만들기
; https://www.sysnet.pe.kr/2/0/12216

.NET Framework: 905. C# - DirectX 게임 클라이언트 실행 중 키보드 입력을 감지하는 방법
; https://www.sysnet.pe.kr/2/0/12218

.NET Framework: 917. C# - USB 관련 ETW(Event Tracing for Windows)를 이용한 키보드 입력을 감지하는 방법
; https://www.sysnet.pe.kr/2/0/12246

.NET Framework: 990. C# - SendInput Win32 API를 이용한 가상 키보드/마우스
; https://www.sysnet.pe.kr/2/0/12469

개발 환경 구성: 607. 로컬의 USB 장치를 원격 머신에 제공하는 방법 - usbip-win
; https://www.sysnet.pe.kr/2/0/12858




(User-mode 코드로 가상 USB 장치를 만들 수 있는) USB/IP PROJECT 소개

오호... 이런 프로젝트가 있었군요. ^^

USB/IP PROJECT
; http://usbip.sourceforge.net

당연히 소스 코드도 공개되어 있어 직접 빌드하는 것도 가능하지만,

The USB/IP Project
; https://sourceforge.net/p/usbip/git-windows

OS 드라이버에 대한 Signing 문제를 생각하면 그냥 빌드된 드라이버를 사용하는 것이 더 좋을 듯합니다. 물론, 커널에 올라가는 실행 모듈이니만큼 신뢰성 측면에서 주의를 해야 하지만 React 프로젝트에서 서명을 해줄 정도면 크게 문제가 있어 보이진 않습니다.




사용법을 볼까요?

README for Windows
; https://sourceforge.net/p/usbip/git-windows/ci/master/tree/trunk/driver/USAGE

다음의 파일을 내려받아 압축 해제하고,

usbip_windows_v0.2.0.0_signed.zip
; https://sourceforge.net/projects/usbip/files/usbip_windows/

장치 관리자를 통해 "Action" / "Add legacy hardware" 메뉴로 뜨는 창에서 "Install the hardware that I manually select from a list (Advanced)", "Have Disk ..."로 들어가 압축 해제한 폴더의 "USBIPEnum.inf" 파일을 지정하면 "USB/IP Enumerator" 장치가 "System devices" 하위 노드로 생성됩니다. 이것으로 가상 USB 장치를 네트워크로부터 붙일 준비를 마쳤습니다. (이 글에서는 USB/IP Enumerator가 설치된 PC의 IP가 192.168.100.50이라고 가정합니다.)




자, 그럼 USB/IP이니만큼 다른 컴퓨터(또는 로컬)에서 가상 USB 장치를 생성할 수 있다는 건데요, 해당 장치를 Python 코드로 맞춰주는 방법을 다음의 글에서 소개하고 있습니다.

Emulating USB Devices In Python With No Additional Hardware!
; https://breaking-the-system.blogspot.com/2014/08/emulating-usb-devices-in-python-with-no.html

smulikHakipod / USB-Emulation
; https://github.com/smulikHakipod/USB-Emulation

그래서 위의 USB-Emulation에 공개된 USBIP.py와 hid.py를 내려받아 다음과 같이 Python 2.7 버전으로 실행해 주면,

c:\temp> python hid.py

소켓 대기를 하게 되고, "USB/IP Enumerator" 장치를 설치한 서버 측에서 usbip.exe를 실행해 hid.py가 구현한 가상 장치를 연결할 수 있습니다. 예를 들어, hid.py를 실행해 놓은 PC의 IP 주소가 192.168.100.25라고 하면 다음과 같이 실행하면 됩니다.

// "USB/IP Enumerator"가 설치된 PC(192.168.100.50)에서 hid.py가 실행 중인 PC(192.168.100.25)로 연결

c:\temp> usbip -a 192.168.100.25 "1-1"

그럼 2개의 프로그램에서 서로 통신하면서,

c:\temp> usbip -a 192.168.100.25 "1-1"
new usb device attached to usbvbus port 1

c:\temp> python hid.py
Connection address: ('192.168.100.50', 2175)
Header Packet
command: 0x8005
list of devices
Connection address: ('192.168.100.50', 2176)
Header Packet
command: 0x8003
attach device
handles requests
handles requests
handles requests
handles requests
Idle
handles requests
send initial report
handles requests
handles requests
handles requests

(hid.py가 마우스 장치로써 인식할 수 있도록 만들어졌으므로) "USB/IP Enumerator" 장치를 설치한 서버 측에는 다음과 같이 새로운 마우스 하나가 인식이 됩니다.

usbip_device_driver_1.png

이때의 이벤트 로그를 보면 다음의 구성으로 연결된 장치를 확인할 수 있습니다.

Device HID\Vid_0627&Pid_0000\2&168cb114&0&0000 was configured.

Driver Name: msmouse.inf
Class Guid: {4d36e96f-e325-11ce-bfc1-08002be10318}
Driver Date: 06/21/2006
Driver Version: 10.0.18362.1
Driver Provider: Microsoft
Driver Section: HID_Mouse_Inst.NT
Driver Rank: 0xFF1003
Matching Device Id: HID_DEVICE_SYSTEM_MOUSE
Outranked Drivers: input.inf:HID_DEVICE:00FF1005
Device Updated: false
Parent Device: USB\Vid_0627&Pid_0000\1&79f5d87&0&01

참고로, hid.py 소스 코드를 보면 5초 동안 마우스 데이터를 보내는 듯 한데,

def handle_data(self, usb_req):
    # Sending random mouse data
    # Send data only for 5 seconds
    if (datetime.datetime.now() - self.start_time).seconds < 5:
        return_val = chr(0x0) + chr(random.randint(1, 10)) + chr(random.randint(1, 10)) + chr(random.randint(1, 10))
        self.send_usb_req(usb_req, return_val)

실제로 해보니 동작이 안 됩니다. (혹시 성공하셨거나, 이유를 아시는 분은 덧글 부탁드립니다.)




위의 예제를 바탕으로 키보드 장치까지 구현한 예제가 다음의 github repo에 있습니다. (Python과 C 언어 버전을 제공합니다.)

lcgamboa / USBIP-Virtual-USB-Device
; https://github.com/lcgamboa/USBIP-Virtual-USB-Device

USBIP-Virtual-USB-Device/python/hid-keyboard.py
; https://github.com/lcgamboa/USBIP-Virtual-USB-Device/blob/master/python/hid-keyboard.py

마찬가지로 python 2.7 버전으로 실행해 두면,

c:\temp> python.exe hid-keyboard.py

서버 측에서 usbip.exe를 이용해 연결하면 됩니다.

c:\temp> usbip -a 192.168.100.25 "1-1"

그런데, 실제로 해보면 다음과 같이 버전 불일치 오류가 발생합니다.

c:\temp> python.exe hid-keyboard.py
Connection address: ('192.168.100.50', 49810)
Header Packet
command: 0x8005
list of devices
Traceback (most recent call last):
  File "hid-keyboard.py", line 164, in <module>
    usb_container.run()
  File "C:\USBIP-Virtual-USB-Device\python\USBIP.py", line 420, in run
    data = conn.recv(8)
socket.error: [Errno 10054] An existing connection was forcibly closed by the remote host

c:\temp> usbip -a 192.168.100.25 "1-1"
usbip err: usbip_network.c: 128 (usbip_recv_op_common) version mismatch, 273 262
usbip err: usbip_windows.c: 756 (query_interface0) recv op_common
usbip err: usbip_windows.c: 829 (attach_device) cannot find device

아마도, 해당 개발자가 테스트한 서버의 빌드가 (공개되지 않은) 더 최신 버전으로 보이는데, 그냥 USBIP.py 소스 코드의 버전을 다음과 같이 262로 변경해도 (테스트한 바로는) 잘 동작합니다.

class USBIPHeader(BaseStucture):
    _fields_ = [
        ('version', 'H', 262),
        ('command', 'H'),
        ('status', 'I')
    ]

일단, 실행이 잘 되면 handle_data의 구현 코드로 인해 무작위 글자 100/2 개가 전송됩니다.

def handle_data(self, usb_req):
    # Sending random keyboard data
    # Send data only for 5 seconds
    #if (datetime.datetime.now() - self.start_time).seconds < 10:
    print "handle data"
    global count
    if count < 100:
        if (count % 2) == 0:
            return_val = "\x00\x00" + str(chr(random.randint(4,29))) + "\x00\x00\x00\x00\x00"
        else: 
            return_val = "\x00\x00\x00\x00\x00\x00\x00\x00"
        self.send_usb_req(usb_req, return_val, len(return_val))
    time.sleep(0.05)
    count=count+1




그런데, 한 가지 문제가 있습니다. 해당 장치를 detach 시키면,

c:\temp> usbip -d 1-1

Windows 10에서 DRIVER_IRQL_NOT_LESS_OR_EQUAL 오류 메시지로 BSOD가 발생합니다.

Windows Client v.0.2.0.0 Problems
; https://sourceforge.net/p/usbip/discussion/418507/thread/7ff86875/?page=0

아쉽군요, 현재 이 프로젝트는 개발이 중지된 상태이므로 더 이상의 업데이트를 기대할 수 없어 현실적인 수준에서 쓰기에는 무리가 있는 상태입니다. (대신 다른 대안이 있는데, 다음 글에서 이에 관해 정리해 보겠습니다. ^^)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 11/29/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...
NoWriterDateCnt.TitleFile(s)
13600정성태4/18/2024215닷넷: 2242. C# - 관리 스레드와 비관리 스레드
13599정성태4/17/2024259닷넷: 2241. C# - WAV 파일의 PCM 사운드 재생(Windows Multimedia)파일 다운로드1
13598정성태4/16/2024274닷넷: 2240. C# - WAV 파일 포맷 + LIST 헤더파일 다운로드1
13597정성태4/15/2024338닷넷: 2239. C# - WAV 파일의 PCM 데이터 생성 및 출력파일 다운로드1
13596정성태4/14/2024667닷넷: 2238. C# - WAV 기본 파일 포맷파일 다운로드1
13595정성태4/13/2024789닷넷: 2237. C# - Audio 장치 열기 (Windows Multimedia, NAudio)파일 다운로드1
13594정성태4/12/2024989닷넷: 2236. C# - Audio 장치 열람 (Windows Multimedia, NAudio)파일 다운로드1
13593정성태4/8/20241045닷넷: 2235. MSBuild - AccelerateBuildsInVisualStudio 옵션
13592정성태4/2/20241202C/C++: 165. CLion으로 만든 Rust Win32 DLL을 C#과 연동
13591정성태4/2/20241164닷넷: 2234. C# - WPF 응용 프로그램에 Blazor App 통합파일 다운로드1
13590정성태3/31/20241071Linux: 70. Python - uwsgi 응용 프로그램이 k8s 환경에서 OOM 발생하는 문제
13589정성태3/29/20241138닷넷: 2233. C# - 프로세스 CPU 사용량을 나타내는 성능 카운터와 Win32 API파일 다운로드1
13588정성태3/28/20241191닷넷: 2232. C# - Unity + 닷넷 App(WinForms/WPF) 간의 Named Pipe 통신파일 다운로드1
13587정성태3/27/20241149오류 유형: 900. Windows Update 오류 - 8024402C, 80070643
13586정성태3/27/20241292Windows: 263. Windows - 복구 파티션(Recovery Partition) 용량을 늘리는 방법
13585정성태3/26/20241092Windows: 262. PerformanceCounter의 InstanceName에 pid를 추가한 "Process V2"
13584정성태3/26/20241046개발 환경 구성: 708. Unity3D - C# Windows Forms / WPF Application에 통합하는 방법파일 다운로드1
13583정성태3/25/20241149Windows: 261. CPU Utilization이 100% 넘는 경우를 성능 카운터로 확인하는 방법
13582정성태3/19/20241222Windows: 260. CPU 사용률을 나타내는 2가지 수치 - 사용량(Usage)과 활용률(Utilization)파일 다운로드1
13581정성태3/18/20241585개발 환경 구성: 707. 빌드한 Unity3D 프로그램을 C++ Windows Application에 통합하는 방법
13580정성태3/15/20241136닷넷: 2231. C# - ReceiveTimeout, SendTimeout이 적용되지 않는 Socket await 비동기 호출파일 다운로드1
13579정성태3/13/20241493오류 유형: 899. HTTP Error 500.32 - ANCM Failed to Load dll
13578정성태3/11/20241627닷넷: 2230. C# - 덮어쓰기 가능한 환형 큐 (Circular queue)파일 다운로드1
13577정성태3/9/20241864닷넷: 2229. C# - 닷넷을 위한 난독화 도구 소개 (예: ConfuserEx)
13576정성태3/8/20241543닷넷: 2228. .NET Profiler - IMetaDataEmit2::DefineMethodSpec 사용법
[1]  2  3  4  5  6  7  8  9  10  11  12  13  14  15  ...