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)
13426정성태10/13/20233290스크립트: 59. 파이썬 - 비동기 호출 함수(run_until_complete, run_in_executor, create_task, run_in_threadpool)
13425정성태10/11/20233105닷넷: 2149. C# - PLinq의 Partitioner<T>를 이용한 사용자 정의 분할파일 다운로드1
13423정성태10/6/20233085스크립트: 58. 파이썬 - async/await 기본 사용법
13422정성태10/5/20233224닷넷: 2148. C# - async 유무에 따른 awaitable 메서드의 병렬 및 예외 처리
13421정성태10/4/20233255닷넷: 2147. C# - 비동기 메서드의 async 예약어 유무에 따른 차이
13420정성태9/26/20235361스크립트: 57. 파이썬 - UnboundLocalError: cannot access local variable '...' where it is not associated with a value
13419정성태9/25/20233111스크립트: 56. 파이썬 - RuntimeError: dictionary changed size during iteration
13418정성태9/25/20233791닷넷: 2146. C# - ConcurrentDictionary 자료 구조의 동기화 방식
13417정성태9/19/20233357닷넷: 2145. C# - 제네릭의 형식 매개변수에 속한 (매개변수를 가진) 생성자를 호출하는 방법
13416정성태9/19/20233161오류 유형: 877. redis-py - MISCONF Redis is configured to save RDB snapshots, ...
13415정성태9/18/20233643닷넷: 2144. C# 12 - 컬렉션 식(Collection Expressions)
13414정성태9/16/20233410디버깅 기술: 193. Windbg - ThreadStatic 필드 값을 조사하는 방법
13413정성태9/14/20233606닷넷: 2143. C# - 시스템 Time Zone 변경 시 이벤트 알림을 받는 방법
13412정성태9/14/20236878닷넷: 2142. C# 12 - 인라인 배열(Inline Arrays) [1]
13411정성태9/12/20233388Windows: 252. 권한 상승 전/후 따로 관리되는 공유 네트워크 드라이브 정보
13410정성태9/11/20234895닷넷: 2141. C# 12 - Interceptor (컴파일 시에 메서드 호출 재작성) [1]
13409정성태9/8/20233751닷넷: 2140. C# - Win32 API를 이용한 모니터 전원 끄기
13408정성태9/5/20233739Windows: 251. 임의로 만든 EXE 파일을 포함한 ZIP 파일의 압축을 해제할 때 Windows Defender에 의해 삭제되는 경우
13407정성태9/4/20233497닷넷: 2139. C# - ParallelEnumerable을 이용한 IEnumerable에 대한 병렬 처리
13406정성태9/4/20233451VS.NET IDE: 186. Visual Studio Community 버전의 라이선스
13405정성태9/3/20233871닷넷: 2138. C# - async 메서드 호출 원칙
13404정성태8/29/20233398오류 유형: 876. Windows - 키보드의 등호(=, Equals sign) 키가 눌리지 않는 경우
13403정성태8/21/20233232오류 유형: 875. The following signatures couldn't be verified because the public key is not available: NO_PUBKEY EB3E94ADBE1229CF
13402정성태8/20/20233298닷넷: 2137. ILSpy의 nuget 라이브러리 버전 - ICSharpCode.Decompiler
13401정성태8/19/20233537닷넷: 2136. .NET 5+ 환경에서 P/Invoke의 성능을 높이기 위한 SuppressGCTransition 특성 [1]
13400정성태8/10/20233376오류 유형: 874. 파이썬 - pymssql을 윈도우 환경에서 설치 불가
1  2  3  4  5  6  7  [8]  9  10  11  12  13  14  15  ...