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

비밀번호

댓글 작성자
 




... 31  32  33  34  35  [36]  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12736정성태7/28/20217349오류 유형: 743. Active Azure Directory에서 "API permissions"의 권한 설정이 "Not granted for ..."로 나오는 문제
12735정성태7/27/20217848.NET Framework: 1081. C# - Azure AD 인증을 지원하는 데스크톱 애플리케이션 예제(Windows Forms) [2]파일 다운로드1
12734정성태7/26/202123841스크립트: 20. 특정 단어로 시작하거나/끝나는 문자열을 포함/제외하는 정규 표현식 - Look-around
12733정성태7/23/202111176.NET Framework: 1081. Self-Contained/SingleFile 유형의 .NET Core/5+ 실행 파일을 임베딩한다면? [1]파일 다운로드2
12732정성태7/23/20216457오류 유형: 742. SharePoint - The super user account utilized by the cache is not configured.
12731정성태7/23/20217681개발 환경 구성: 584. Add Internal URLs 화면에서 "Save" 버튼이 비활성화 된 경우
12730정성태7/23/20219191개발 환경 구성: 583. Visual Studio Code - Go 코드에서 입력을 받는 경우
12729정성태7/22/20218135.NET Framework: 1080. xUnit 단위 테스트에 메서드/클래스 수준의 문맥 제공 - Fixture
12728정성태7/22/20217596.NET Framework: 1079. MSTestv2 단위 테스트에 메서드/클래스/어셈블리 수준의 문맥 제공
12727정성태7/21/20218608.NET Framework: 1078. C# 단위 테스트 - MSTestv2/NUnit의 Assert.Inconclusive 사용법(?) [1]
12726정성태7/21/20218432VS.NET IDE: 169. 비주얼 스튜디오 - 단위 테스트 선택 시 MSTestv2 외의 xUnit, NUnit 사용법 [1]
12725정성태7/21/20217121오류 유형: 741. Failed to find the "go" binary in either GOROOT() or PATH
12724정성태7/21/20219815개발 환경 구성: 582. 윈도우 환경에서 Visual Studio Code + Go (Zip) 개발 환경 [1]
12723정성태7/21/20217469오류 유형: 740. SharePoint - Alternate access mappings have not been configured 경고
12722정성태7/20/20217302오류 유형: 739. MSVCR110.dll이 없어 exe 실행이 안 되는 경우
12721정성태7/20/20217922오류 유형: 738. The trust relationship between this workstation and the primary domain failed. - 세 번째 이야기
12720정성태7/19/20217275Linux: 43. .NET Core/5+ 응용 프로그램의 Ubuntu (Debian) 패키지 준비
12719정성태7/19/20216452오류 유형: 737. SharePoint 설치 시 "0x800710D8 The object identifier does not represent a valid object." 오류 발생
12718정성태7/19/20217058개발 환경 구성: 581. Windows에서 WSL로 파일 복사 시 root 소유권으로 적용되는 문제파일 다운로드1
12717정성태7/18/20217001Windows: 195. robocopy에서 파일의 ADS(Alternate Data Stream) 정보 복사를 제외하는 방법
12716정성태7/17/20217811개발 환경 구성: 580. msbuild의 Exec Task에 robocopy를 사용하는 방법파일 다운로드1
12715정성태7/17/20219462오류 유형: 736. Windows - MySQL zip 파일 버전의 "mysqld --skip-grant-tables" 실행 시 비정상 종료 [1]
12714정성태7/16/20218241오류 유형: 735. VCRUNTIME140.dll, MSVCP140.dll, VCRUNTIME140.dll, VCRUNTIME140_1.dll이 없어 exe 실행이 안 되는 경우
12713정성태7/16/20218774.NET Framework: 1077. C# - 동기 방식이면서 비동기 규약을 따르게 만드는 Task.FromResult파일 다운로드1
12712정성태7/15/20218206개발 환경 구성: 579. Azure - 리눅스 호스팅의 Site Extension 제작 방법
12711정성태7/15/20218540개발 환경 구성: 578. Azure - Java Web App Service를 위한 Site Extension 제작 방법
... 31  32  33  34  35  [36]  37  38  39  40  41  42  43  44  45  ...