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

비밀번호

댓글 작성자
 




... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13030정성태4/15/20226496오류 유형: 804. 정규 표현식 오류 - Quantifier {x,y} following nothing.
13029정성태4/14/20226899Windows: 203. iisreset 후에도 이전에 설정한 전역 환경 변수가 w3wp.exe에 적용되는 문제
13028정성태4/13/20226809.NET Framework: 1193. (appsettings.json처럼) web.config의 Debug/Release에 따른 설정 적용
13027정성태4/12/20227102.NET Framework: 1192. C# - 환경 변수의 변화를 알리는 WM_SETTINGCHANGE Win32 메시지 사용법파일 다운로드1
13026정성태4/11/20228633.NET Framework: 1191. C 언어로 작성된 FFmpeg Examples의 C# 포팅 전체 소스 코드 [3]
13025정성태4/11/20227972.NET Framework: 1190. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 vaapi_encode.c, vaapi_transcode.c 예제 포팅
13024정성태4/7/20226465.NET Framework: 1189. C# - 런타임 환경에 따라 달라진 AppDomain.GetCurrentThreadId 메서드
13023정성태4/6/20226767.NET Framework: 1188. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 transcoding.c 예제 포팅 [3]
13022정성태3/31/20226671Windows: 202. 윈도우 11 업그레이드 - "PC Health Check"를 통과했지만 여전히 업그레이드가 안 되는 경우 해결책
13021정성태3/31/20226841Windows: 201. Windows - INF 파일을 이용한 장치 제거 방법
13020정성태3/30/20226581.NET Framework: 1187. RDP 접속 시 WPF UserControl의 Unloaded 이벤트 발생파일 다운로드1
13019정성태3/30/20226575.NET Framework: 1186. Win32 Message를 Code로부터 메시지 이름 자체를 구하고 싶다면?파일 다운로드1
13018정성태3/29/20227117.NET Framework: 1185. C# - Unsafe.AsPointer가 반환한 포인터는 pinning 상태일까요? [5]
13017정성태3/28/20226917.NET Framework: 1184. C# - GC Heap에 위치한 참조 개체의 주소를 알아내는 방법 - 두 번째 이야기 [3]
13016정성태3/27/20227770.NET Framework: 1183. C# 11에 추가된 ref 필드의 (우회) 구현 방법파일 다운로드1
13015정성태3/26/20229123.NET Framework: 1182. C# 11 - ref struct에 ref 필드를 허용 [1]
13014정성태3/23/20227694VC++: 155. CComPtr/CComQIPtr과 Conformance mode 옵션의 충돌 [1]
13013정성태3/22/20226025개발 환경 구성: 641. WSL 우분투 인스턴스에 파이썬 2.7 개발 환경 구성하는 방법
13012정성태3/21/20225348오류 유형: 803. C# - Local '...' or its members cannot have their address taken and be used inside an anonymous method or lambda expression
13011정성태3/21/20226827오류 유형: 802. 윈도우 운영체제에서 웹캠 카메라 인식이 안 되는 경우
13010정성태3/21/20225752오류 유형: 801. Oracle.ManagedDataAccess.Core - GetTypes 호출 시 "Could not load file or assembly 'System.DirectoryServices.Protocols...'" 오류
13009정성태3/20/20227380개발 환경 구성: 640. docker - ibmcom/db2 컨테이너 실행
13008정성태3/19/20226675VS.NET IDE: 176. 비주얼 스튜디오 - 솔루션 탐색기에서 프로젝트를 선택할 때 csproj 파일이 열리지 않도록 만드는 방법
13007정성태3/18/20226259.NET Framework: 1181. C# - Oracle.ManagedDataAccess의 Pool 및 그것의 연결 개체 수를 알아내는 방법파일 다운로드1
13006정성태3/17/20227335.NET Framework: 1180. C# - ffmpeg(FFmpeg.AutoGen)를 이용한 remuxing.c 예제 포팅
13005정성태3/17/20226200오류 유형: 800. C# - System.InvalidOperationException: Late bound operations cannot be performed on fields with types for which Type.ContainsGenericParameters is true.
... 16  17  18  19  20  21  22  23  [24]  25  26  27  28  29  30  ...