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)
13526정성태1/14/20242048닷넷: 2201. C# - Facebook 연동 / 사용자 탈퇴 처리 방법
13525정성태1/13/20242015오류 유형: 891. Visual Studio - Web Application을 실행하지 못하는 IISExpress
13524정성태1/12/20242064오류 유형: 890. 한국투자증권 KIS Developers OpenAPI - GW라우팅 중 오류가 발생했습니다.
13523정성태1/12/20241888오류 유형: 889. Visual Studio - error : A project with that name is already opened in the solution.
13522정성태1/11/20242026닷넷: 2200. C# - HttpClient.PostAsJsonAsync 호출 시 "Transfer-Encoding: chunked" 대신 "Content-Length" 헤더 처리
13521정성태1/11/20242108닷넷: 2199. C# - 한국투자증권 KIS Developers OpenAPI의 WebSocket Ping, Pong 처리
13520정성태1/10/20241858오류 유형: 888. C# - Unable to resolve service for type 'Microsoft.Extensions.ObjectPool.ObjectPool`....'
13519정성태1/10/20241937닷넷: 2198. C# - Reflection을 이용한 ClientWebSocket의 Ping 호출파일 다운로드1
13518정성태1/9/20242172닷넷: 2197. C# - ClientWebSocket의 Ping, Pong 처리
13517정성태1/8/20242015스크립트: 63. Python - 공개 패키지를 이용한 위성 이미지 생성 (pystac_client, odc.stac)
13516정성태1/7/20242102닷넷: 2196. IIS - AppPool의 "Disable Overlapped Recycle" 옵션의 부작용
13515정성태1/6/20242374닷넷: 2195. async 메서드 내에서 C# 7의 discard 구문 활용 사례 [1]
13514정성태1/5/20242064개발 환경 구성: 702. IIS - AppPool의 "Disable Overlapped Recycle" 옵션
13513정성태1/5/20242003닷넷: 2194. C# - WebActivatorEx / System.Web의 PreApplicationStartMethod 특성
13512정성태1/4/20241979개발 환경 구성: 701. IIS - w3wp.exe 프로세스의 ASP.NET 런타임을 항상 Warmup 모드로 유지하는 preload Enabled 설정
13511정성태1/4/20241995닷넷: 2193. C# - ASP.NET Web Application + OpenAPI(Swashbuckle) 스펙 제공
13510정성태1/3/20241935닷넷: 2192. C# - 특정 실행 파일이 있는지 확인하는 방법 (Linux)
13509정성태1/3/20241966오류 유형: 887. .NET Core 2 이하의 프로젝트에서 System.Runtime.CompilerServices.Unsafe doesn't support netcoreapp2.0.
13508정성태1/3/20242012오류 유형: 886. ORA-28000: the account is locked
13507정성태1/2/20242695닷넷: 2191. C# - IPGlobalProperties를 이용해 netstat처럼 사용 중인 Socket 목록 구하는 방법파일 다운로드1
13506정성태12/29/20232187닷넷: 2190. C# - 닷넷 코어/5+에서 달라지는 System.Text.Encoding 지원
13505정성태12/27/20232702닷넷: 2189. C# - WebSocket 클라이언트를 닷넷으로 구현하는 예제 (System.Net.WebSockets)파일 다운로드1
13504정성태12/27/20232318닷넷: 2188. C# - ASP.NET Core SignalR로 구현하는 채팅 서비스 예제파일 다운로드1
13503정성태12/27/20232189Linux: 67. WSL 환경 + mlocate(locate) 도구의 /mnt 디렉터리 검색 문제
13502정성태12/26/20232289닷넷: 2187. C# - 다른 프로세스의 환경변수 읽는 예제파일 다운로드1
13501정성태12/25/20232087개발 환경 구성: 700. WSL + uwsgi - IPv6로 바인딩하는 방법
1  2  3  [4]  5  6  7  8  9  10  11  12  13  14  15  ...