simulating keystroke on the remote machine you sshed to

Pre

Assuming you have a machine connected to a monitor or television as a movie player, and the tv maybe keep a distance from you since you wouldn’t like to watch movies so close to it.

Issue

The machine is away from you which make it inconvenient to control it.

  1. Physical way: connect a keyboard with long wire or a wireless bluetooth one. For mouse, options are few here, a wireless one should be great.
  2. Remote way: use another machine to control it.

Since I don’t have a wireless keyboard, I’d like to try the remote way.
Also I don’t want a keyboard lie besides my pillow, but I can bear a computer though since I have to use it anyway.

It’s easy to imageine that there’re some softwares focusing on solving this kind of problem by control mouse and keyboard input remotely.
However they’re almost all gui based tools, which is unfriendly for me, because I’d like to work in a pure tty with archlinux or something.

So I have to make it work on my own.

Solution

  1. Ssh into the remote machine,
  2. Read the keyboard input
  3. Since the remote one is a macbook, I have to execute osascript to simulate keyboard keystroke according to the input read from terminal.
    We achieve this by writing a script to receive the input and convert it into a osascript.
    When you want to simulate the keyboard input, execute the script.
flowchart LR

    subgraph B[By side Machine]
        t(tty)
    end

    t -.- |ssh| T
    t --> |input| s

    subgraph R[Remote Machie]
       subgraph T[terminal]
        s(sh script)
       end
        s --> o(osascript)
        o --> k
       subgraph k[simulate keyboard]
       end
     end

Source

This is a very basic and rough one, you should edit it to make it work better.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#! /bin/bash

IFS=""
while true; do
read -rsn1 input
case "$input" in

"1")
osascript -e 'tell application "System Events" to keystroke "1"'
;;

"a")
osascript -e 'tell application "System Events" to keystroke "a"'
;;
"z")
osascript -e 'tell application "System Events" to keystroke "z"'
;;


"A")
osascript -e 'tell application "System Events" to keystroke "A"'
;;
"Z")
osascript -e 'tell application "System Events" to keystroke "Z"'
;;


$'\t')
osascript -e 'tell application "System Events" to keystroke tab'
;;
" ")
echo "space"
osascript -e 'tell application "System Events" to key code 49'
;;
$'\x7f')
echo "backspace"
osascript -e 'tell application "System Events" to key code 51'
;;
"")
echo "enter"
osascript -e 'tell application "System Events" to key code 36'
;;


$'\x1b')
# read next input char to confirm the key sequence
read -rsn2 input2

case "$input2" in
"[A")
echo "arrow up"
;;
esac
;;

"*")
echo "invalid input"

;;
esac
done