add basic key automation

This commit is contained in:
Frédéric Péters 2021-06-05 21:45:55 +02:00
parent 11b21739cb
commit 4f3180eb37
2 changed files with 49 additions and 0 deletions

10
README
View File

@ -64,6 +64,16 @@ variables, ex::
env1 = PS1=LANG=C.UTF-8
There is also basic support for automation, mostly for situations where
key-based authentication is not possible. Server sections can have expect and
send entries, when the output ends with an expected string the "send" keys will
be sent (as well as a carriage return), ex::
[server:server1.local]
expect = password:
send = my_password
Examples
--------

View File

@ -102,6 +102,17 @@ def get_servers():
tags = [x.strip() for x in config.get('servers', server).split(',')]
servers.append(Server(servername, tags, display_name=get_display_name(servername)))
for server in servers:
if config.has_section('server:%s' % server.name):
# server.key_automation will be a list
# [content to expect, list of keys to send]
server.key_automation = []
for key, value in sorted(config.items('server:%s' % server.name)):
if key.startswith('expect'):
server.key_automation.append([value, []])
elif key.startswith('send'):
server.key_automation[-1][1].append(value)
return servers
@ -401,6 +412,32 @@ else:
server_info['status'] = 'done'
send_status_message(tmux_session_name, {'@type': 'servers-info', 'info': servers_info})
def handle_expects():
for win in session.list_windows():
try:
server = [x for x in all_servers if x.name == win.name][0]
except IndexError:
continue
if not getattr(server, 'key_automation', None):
continue
try:
current_content = win.cmd('capture-pane', '-p').stdout[-1]
except IndexError:
pass
else:
if current_content.endswith(server.key_automation[0][0]):
for keys in server.key_automation[0][1]:
# pane.send_keys sends a leading space character and
# that makes it unusuable to send a password (for
# example).
try:
win.panes[0].cmd('send-keys', keys + '\n')
except IndexError:
continue
time.sleep(0.1)
# remove played automation
server.key_automation = server.key_automation[1:]
while selected_servers:
current_clusters = [cluster_name(x.name) for x in session.list_windows()]
for server in selected_servers[:]:
@ -421,6 +458,7 @@ else:
time.sleep(0.1)
while len(session.list_windows()) > 10:
send_status()
handle_expects()
time.sleep(0.1)
send_status()
@ -436,6 +474,7 @@ else:
while len(session.list_windows()) > 1:
send_status()
handle_expects()
time.sleep(0.1)
status_window.rename_window('🌕')
send_status()