-
Notifications
You must be signed in to change notification settings - Fork 110
/
shutit_pexpect_session.py
3673 lines (3438 loc) · 161 KB
/
shutit_pexpect_session.py
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# The MIT License (MIT)
#
# Copyright (C) 2014 OpenBet Limited
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
# of the Software, and to permit persons to whom the Software is furnished to do
# so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
# THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
"""Represents and manages a pexpect object for ShutIt's purposes.
ShutItGlobal
|
- set(ShutItPexpectSessionEnvironment) - environments can exist in multiple sessions (eg root one)
|
-ShutItLoginStack
|
- ShutItLoginStackItem[]
|
- ShutItBackgroundCommand[]
ShutIt
|
- current_pexpect_session
|
- dict(ShutItPexpectSessions)
|
- each ShutItPexpectSession contains a current ShutItPexpectSessionEnvironment object
"""
from __future__ import print_function
try:
from md5 import md5
except ImportError: # pragma: no cover
from hashlib import md5
import logging
import string
import time
import os
import re
import base64
import sys
import textwrap
import pexpect
import shutit_util
import shutit_global
from shutit_global import SessionPaneLine
import package_map
import shutit_class
from shutit_login_stack import ShutItLoginStack
from shutit_sendspec import ShutItSendSpec
from shutit_module import ShutItFailException
from shutit_pexpect_session_environment import ShutItPexpectSessionEnvironment
from shutit_background import ShutItBackgroundCommand
if sys.version_info[0] >= 3:
unicode = str
class ShutItPexpectSession(object):
def __init__(self,
shutit,
pexpect_session_id,
command,
args=None,
timeout=shutit_global.shutit_global_object.default_timeout,
maxread=2000,
searchwindowsize=None,
env=None,
ignore_sighup=False,
echo=True,
preexec_fn=None,
encoding=None,
codec_errors='strict',
dimensions=None,
delaybeforesend=None):
"""spawn a child, and manage the delaybefore send setting to 0
"""
# If encoding is set, then pexpect returns data in that encoding.
# Otherwise, it returns it in bytes. bytes() has different args in PY2
# and PY3, hence this shuffling. There may be a better way to do this.
# TODO: spawn encoding in PY2 and handle appropriately there also.
if not encoding and shutit_global.shutit_global_object.ispy3: # pragma: no cover
encoding = shutit_global.shutit_global_object.default_encoding
assert isinstance(shutit, shutit_class.ShutIt), shutit_util.print_debug()
self.shutit = shutit
self.check_exit = True
self.default_expect = [shutit_global.shutit_global_object.base_prompt]
# shell_expect stores the expected expect if we are in a shell.
self.shell_expect = self.default_expect
# A flag indicating whether we are in a shell.
self.in_shell = True
self.pexpect_session_id = pexpect_session_id
self.pexpect_session_number = len(shutit_global.get_shutit_pexpect_sessions()) + 1
self.login_stack = ShutItLoginStack(shutit_obj=shutit)
self.current_environment = None
args = args or []
if not delaybeforesend:
delaybeforesend=shutit_global.shutit_global_object.delaybeforesend
# The pane to which this pexpect session is assigned.
self.pexpect_session_pane = None
# Array of SessionPaneLine objects
self.session_output_lines = []
self.pexpect_child = self._spawn_child(command=command,
args=args,
timeout=timeout,
maxread=maxread,
searchwindowsize=searchwindowsize,
env=env,
ignore_sighup=ignore_sighup,
echo=echo,
preexec_fn=preexec_fn,
encoding=encoding,
codec_errors=codec_errors,
dimensions=dimensions,
delaybeforesend=delaybeforesend)
def __str__(self):
str_repr = '\n======= SHUTIT_PEXPECT_SESSION BEGIN ======='
str_repr += '\nSHUTIT_PEXPECT_SESSION check_exit=' + str(self.check_exit)
str_repr += '\nSHUTIT_PEXPECT_SESSION default_expect=' + str(self.default_expect)
str_repr += '\nSHUTIT_PEXPECT_SESSION shell_expect=' + str(self.shell_expect)
str_repr += '\nSHUTIT_PEXPECT_SESSION in_shell=' + str(self.in_shell)
str_repr += '\nSHUTIT_PEXPECT_SESSION pexpect_session_id=' + str(self.pexpect_session_id)
str_repr += '\nSHUTIT_PEXPECT_SESSION login_stack=' + str(self.login_stack)
str_repr += '\nSHUTIT_PEXPECT_SESSION current_environment=' + str(self.current_environment)
str_repr += '\nSHUTIT_PEXPECT_SESSION pexpect_child=' + str(self.pexpect_child)
str_repr += '\nSHUTIT_PEXPECT_SESSION pexpect_child.before=' + str(self.pexpect_child.before)
str_repr += '\nSHUTIT_PEXPECT_SESSION pexpect_child.after=' + str(self.pexpect_child.after)
str_repr += '\nSHUTIT_PEXPECT_SESSION pexpect_child.buffer=' + str(self.pexpect_child.buffer)
str_repr += '\n======= SHUTIT_PEXPECT_SESSION END ======='
return str_repr
def _spawn_child(self,
command,
args=None,
timeout=shutit_global.shutit_global_object.default_timeout,
maxread=2000,
searchwindowsize=None,
env=None,
ignore_sighup=False,
echo=True,
preexec_fn=None,
encoding=None,
codec_errors='strict',
dimensions=None,
delaybeforesend=shutit_global.shutit_global_object.delaybeforesend):
"""spawn a child, and manage the delaybefore send setting to 0
"""
shutit = self.shutit
args = args or []
pexpect_child = pexpect.spawn(command,
args=args,
timeout=timeout,
maxread=maxread,
searchwindowsize=searchwindowsize,
env=env,
ignore_sighup=ignore_sighup,
echo=echo,
preexec_fn=preexec_fn,
encoding=encoding,
codec_errors=codec_errors,
dimensions=dimensions)
# Set the winsize to the theoretical maximum to reduce risk of trouble from terminal line wraps.
# Other things have been attempted, eg tput rmam/smam without success.
pexpect_child.setwinsize(shutit_global.shutit_global_object.pexpect_window_size[0],shutit_global.shutit_global_object.pexpect_window_size[1])
pexpect_child.delaybeforesend=delaybeforesend
shutit.log('sessions before: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG)
shutit.shutit_pexpect_sessions.update({self.pexpect_session_id:self})
shutit.log('sessions after: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG)
return pexpect_child
def sendline(self, sendspec):
"""Sends line, handling background and newline directives.
True means: 'all handled here ok'
False means: you'll need to 'expect' the right thing from here.
"""
assert not sendspec.started, shutit_util.print_debug()
shutit = self.shutit
shutit.log('Sending in pexpect session (' + str(id(self)) + '): ' + str(sendspec.send), level=logging.DEBUG)
if sendspec.expect:
shutit.log('Expecting: ' + str(sendspec.expect), level=logging.DEBUG)
else:
shutit.log('Not expecting anything', level=logging.DEBUG)
try:
# Check there are no background commands running that have block_other_commands set iff
# this sendspec says
if self._check_blocked(sendspec) and sendspec.ignore_background != True:
shutit.log('sendline: blocked', level=logging.DEBUG)
return False
# If this is marked as in the background, create a background object and run in the background.
if sendspec.run_in_background:
shutit.log('sendline: run_in_background', level=logging.DEBUG)
# If this is marked as in the background, create a background object and run in the background after newlines sorted.
shutit_background_command_object = self.login_stack.get_current_login_item().append_background_send(sendspec)
# Makes no sense to check exit for a background command.
sendspec.check_exit = False
if sendspec.nonewline != True:
sendspec.send += '\n'
# sendspec has newline added now, so no need to keep marker
sendspec.nonewline = True
if sendspec.run_in_background:
shutit_background_command_object.run_background_command()
return True
#shutit.log('sendline: actually sending: ' + sendspec.send, level=logging.DEBUG)
self.pexpect_child.send(sendspec.send)
return False
except OSError:
self.shutit.fail('Caught failure to send, assuming user has exited from pause point.')
# Multisends must go through send() in shutit global
def _check_blocked(self, sendspec):
shutit = self.shutit
if sendspec.ignore_background:
# Do not log the 'normal' case.
#shutit.log('_check_blocked: background is ignored', level=logging.DEBUG)
return False
elif self.login_stack.get_current_login_item():
if self.login_stack.get_current_login_item().find_sendspec(sendspec):
shutit.log('_check_blocked: sendspec object already in there, so GTFO.', level=logging.INFO)
return True
if self.login_stack.get_current_login_item().has_blocking_background_send():
if sendspec.run_in_background:
# If we honour background tasks, and we are running in background, queue it up.
shutit.log('_check_blocked: a blocking background send is running, so queue this up.', level=logging.INFO)
self.login_stack.get_current_login_item().append_background_send(sendspec)
elif not sendspec.run_in_background:
shutit.log('_check_blocked: a blocking background send is running, so queue this up and wait.', level=logging.INFO)
# If we honour background tasts and we are running in foreground, wait.
#sendspec.run_in_background = True
self.login_stack.get_current_login_item().append_background_send(sendspec)
self.wait(sendspec=sendspec)
## Now add this to the background sends.
## And wait until done.
self.wait()
else:
# Should be logically impossible.
assert False, shutit_util.print_debug()
shutit.log('Not yet handled?', level=logging.INFO)
shutit.log(str(sendspec), level=logging.INFO)
return True
else:
# Do not log the 'normal' case
#shutit.log('_check_blocked: no blocking background send', level=logging.DEBUG)
pass
else:
# Do not log the 'normal' case
#shutit.log('_check_blocked: no current login item', level=logging.DEBUG)
pass
return False
def wait(self, cadence=2, sendspec=None):
"""Does not return until all background commands are completed.
"""
shutit = self.shutit
shutit.log('In wait.', level=logging.DEBUG)
if sendspec:
cadence = sendspec.wait_cadence
shutit.log('Login stack is:\n' + str(self.login_stack), level=logging.DEBUG)
while True:
# go through each background child checking whether they've finished
res, res_str, background_object = self.login_stack.get_current_login_item().check_background_commands_complete()
shutit.log('Checking: ' + str(background_object) + '\nres: ' + str(res) + '\nres_str' + str(res_str), level=logging.DEBUG)
if res:
# When all have completed, break return the background command objects.
break
elif res_str in ('S','N'):
# Do nothing, this is an started or not-running task.
pass
elif res_str == 'F':
assert background_object is not None, shutit_util.print_debug()
assert isinstance(background_object, ShutItBackgroundCommand), shutit_util.print_debug()
shutit.log('Failure in: ' + str(self.login_stack), level=logging.DEBUG)
self.pause_point('Background task: ' + background_object.sendspec.original_send + ' :failed.')
return False
else:
self.shutit.fail('Un-handled exit code: ' + res_str) # pragma: no cover
time.sleep(cadence)
shutit.log('Wait complete.', level=logging.DEBUG)
return True
def login(self, sendspec):
"""Logs the user in with the passed-in password and command.
Tracks the login. If used, used logout to log out again.
Assumes you are root when logging in, so no password required.
If not, override the default command for multi-level logins.
If passwords are required, see setup_prompt() and revert_prompt()
@type param: see shutit_sendspec.ShutItSendSpec
@type sendspec: shutit_sendspec.ShutItSendSpec
"""
user = sendspec.user
command = sendspec.send
prompt_prefix = sendspec.prompt_prefix
shutit = self.shutit
# We don't get the default expect here, as it's either passed in, or a base default regexp.
if isinstance(sendspec.password,str):
shutit_global.shutit_global_object.secret_words_set.add(sendspec.password)
r_id = shutit_util.random_id()
if prompt_prefix is None:
prompt_prefix = r_id
# Be helpful - if this looks like a command that requires a user, then suggest user provides one.
if user is None:
user = self.whoami()
if 'bash' not in command:
shutit.log('No user supplied to login function, so retrieving who I am (' + user + '). You may want to override.', level=logging.WARNING)
if ' ' in user:
self.shutit.fail('user has space in it - did you mean: login(command="' + user + '")?') # pragma: no cover
if self.shutit.build['delivery'] == 'bash' and command == 'su -':
# We want to retain the current working directory
command = 'su'
# If this is a su-type command, add the user, else assume user is in the command.
if command == 'su -' or command == 'su' or command == 'login':
send = command + ' ' + user
else:
send = command
login_expect = sendspec.expect or shutit_global.shutit_global_object.base_prompt
# We don't fail on empty before as many login programs mess with the output.
# In this special case of login we expect either the prompt, or 'user@' as this has been seen to work.
general_expect = [login_expect]
# Add in a match if we see user+ and then the login matches. Be careful not to match against '[email protected]:'
general_expect = general_expect + [user+'@.*'+'[#$]']
# If not an ssh login, then we can match against user + @sign because it won't clash with 'user@adasdas password:'
if (sendspec.is_ssh != None and sendspec.is_ssh) or command.find('ssh ') != -1:
shutit.log('Assumed to be an ssh command, is_ssh: ' + str(sendspec.is_ssh) + ', command: ' + command, level=logging.DEBUG)
# If user@ already there, remove it, as it can conflict with password lines in ssh calls.
if user+'@' in general_expect:
general_expect.remove(user+'@')
# Adding the space to avoid commands which embed eg $(whoami) or ${var}
general_expect.append('.*[#$] ')
# Don't match 'Last login:' or 'Last failed login:'
send_dict={'ontinue connecting':['yes', False]}
if sendspec.password is not None:
send_dict.update({'assword:':[sendspec.password, True]})
send_dict.update({r'[^dt] login:':[sendspec.password, True]})
else:
send_dict={'ontinue connecting':['yes', False]}
if sendspec.password is not None:
send_dict.update({'assword:':[sendspec.password, True]})
send_dict.update({r'[^dt] login:':[sendspec.password, True]})
send_dict.update({user+'@':[sendspec.password, True]})
if user == 'bash' and command == 'su -':
shutit.log('WARNING! user is bash - if you see problems below, did you mean: login(command="' + user + '")?', level=logging.WARNING)
self.shutit.handle_note(sendspec.note,command=command + '\n\n[as user: "' + user + '"]',training_input=send)
echo = self.shutit.get_echo_override(sendspec.echo)
shutit.log('Logging in to new ShutIt environment.' + user, level=logging.DEBUG)
shutit.log('Logging in with command: ' + send + ' as user: ' + user, level=logging.DEBUG)
shutit.log('Login stack before login: ' + str(self.login_stack), level=logging.DEBUG)
# check_sudo - set to false if the password has been supplied.
check_sudo = False
if sendspec.password is None and send.strip().find('sudo') == 0:
check_sudo = True
res = self.multisend(ShutItSendSpec(self,
send=send,
send_dict=send_dict,
expect=general_expect,
check_exit=False,
timeout=sendspec.timeout,
fail_on_empty_before=False,
escape=sendspec.escape,
echo=echo,
remove_on_match=True,
nonewline=sendspec.nonewline,
check_sudo=check_sudo,
loglevel=sendspec.loglevel))
if res == -1:
# Should not get here as login should not be blocked.
assert False, shutit_util.print_debug()
# Setup prompt
if prompt_prefix != None:
self.setup_prompt(r_id,prefix=prompt_prefix,capture_exit_code=True)
else:
self.setup_prompt(r_id,capture_exit_code=True)
self.login_stack.append(r_id)
shutit.log('Login stack after login: ' + str(self.login_stack), level=logging.DEBUG)
if self.send_and_get_output(''' echo $SHUTIT_EC && unset SHUTIT_EC''', loglevel=logging.DEBUG, echo=False) != '0':
# TODO: remove just-added login stack item (since we failed to log in successfully)?
if sendspec.fail_on_fail: # pragma: no cover
self.shutit.fail('Login failure! You may want to re-run shutit with --echo or -l debug and scroll up to see what the problem was.')
else:
return False
if sendspec.go_home:
self.send(ShutItSendSpec(self,
send='cd',
check_exit=False,
echo=False,
ignore_background=True,
loglevel=sendspec.loglevel))
self.shutit.handle_note_after(note=sendspec.note,training_input=send)
return True
def logout_all(self, sendspec):
"""Completely logs the user out of all logins in this pexpect session
"""
while self.login_stack.length() > 0:
self.logout(sendspec)
def logout(self, sendspec):
"""Logs the user out. Assumes that login has been called.
If login has never been called, throw an error.
@param command: Command to run to log out (default=exit)
@param note: See send()
"""
# Block until background tasks complete.
self.wait()
shutit = self.shutit
shutit.handle_note(sendspec.note,training_input=sendspec.send)
if self.login_stack.length() > 0:
_ = self.login_stack.pop()
if self.login_stack.length() > 0:
old_prompt_name = self.login_stack.get_current_login_id()
self.default_expect = shutit.expect_prompts[old_prompt_name]
else:
# If none are on the stack, we assume we're going to the root prompt
# set up in shutit_setup.py
shutit.set_default_shutit_pexpect_session_expect()
else:
shutit.fail('Logout called without corresponding login', throw_exception=False) # pragma: no cover
# No point in checking exit here, the exit code will be
# from the previous command from the logged in session
echo = shutit.get_echo_override(sendspec.echo)
output = self.send_and_get_output(sendspec.send,
fail_on_empty_before=False,
timeout=sendspec.timeout,
echo=echo,
loglevel=sendspec.loglevel,
nonewline=sendspec.nonewline)
shutit.handle_note_after(note=sendspec.note)
return output
def setup_prompt(self,
prompt_name,
prefix='default',
capture_exit_code=False,
loglevel=logging.DEBUG):
"""Use this when you've opened a new shell to set the PS1 to something
sane. By default, it sets up the default expect so you don't have to
worry about it and can just call shutit.send('a command').
If you want simple login and logout, please use login() and logout()
within this module.
Typically it would be used in this boilerplate pattern::
shutit.send('su - auser', expect=shutit_global.shutit_global_object.base_prompt, check_exit=False)
shutit.setup_prompt('tmp_prompt')
shutit.send('some command')
[...]
shutit.set_default_shutit_pexpect_session_expect()
shutit.send('exit')
This function is assumed to be called whenever there is a change
of environment.
@param prompt_name: Reference name for prompt.
@param prefix: Prompt prefix. Default: 'default'
@param capture_exit_code: Captures the exit code of the previous
command into a SHUTIT_EC variable. Useful
for when we want to work out whether the
login worked.
@type prompt_name: string
@type prefix: string
"""
shutit = self.shutit
local_prompt = prefix + ':' + shutit_util.random_id() + '# '
shutit.expect_prompts[prompt_name] = local_prompt
# Set up the PS1 value.
# Override the PROMPT_COMMAND as this can cause nasty surprises in the
# output, and we need a short pause before returning the prompt to
# overcome an obscure bash bug (cf.
# https://github.com/pexpect/pexpect/issues/483).
# Set the cols value, as unpleasant escapes are put in the output if the
# input is > n chars wide.
# checkwinsize is required for similar reasons.
# The newline in the expect list is a hack. On my work laptop this line hangs
# and times out very frequently. This workaround seems to work, but I
# haven't figured out why yet - imiell.
# Split the local prompt into two parts and separate with quotes to protect against the expect matching the command rather than the output.
shutit.log('Setting up prompt.', level=logging.DEBUG)
send_str = ''
if capture_exit_code:
send_str = r' SHUTIT_EC=$? && '
send_str += """ export PS1_""" + str(prompt_name) + """=$PS1 && PS1='""" + str(local_prompt[:2]) + "''" + str(local_prompt[2:]) + """' && PROMPT_COMMAND=""" + shutit_global.shutit_global_object.prompt_command
self.send(ShutItSendSpec(self,
send=send_str,
expect=[shutit.expect_prompts[prompt_name]],
fail_on_empty_before=False,
echo=False,
loglevel=loglevel,
ignore_background=True))
# Set default expect to new.
shutit.log('Resetting default expect to: ' + shutit.expect_prompts[prompt_name], level=loglevel)
self.default_expect = shutit.expect_prompts[prompt_name]
# Sometimes stty resets to 0x0 (?), so we must override here.
self.send(ShutItSendSpec(self, send=" stty cols 65535", echo=False, check_exit=False, loglevel=loglevel, ignore_background=True))
self.send(ShutItSendSpec(self, send=" stty rows 65535", echo=False, check_exit=False, loglevel=loglevel, ignore_background=True))
# Avoid dumb terminals
self.send(ShutItSendSpec(self, send=""" if [ $TERM=dumb ];then export TERM=xterm;fi""", echo=False, check_exit=False, loglevel=loglevel, ignore_background=True))
# Get the hostname
# Lack of space after > is deliberate to avoid issues with prompt matching.
hostname = shutit.send_and_get_output(""" if [ $(echo $SHELL) == '/bin/bash' ]; then echo $HOSTNAME; elif [ $(command hostname 2>/dev/null) != '' ]; then hostname -s 2>/dev/null; fi""", echo=False, loglevel=logging.DEBUG)
local_prompt_with_hostname = hostname + ':' + local_prompt
shutit.expect_prompts[prompt_name] = local_prompt_with_hostname
self.default_expect = shutit.expect_prompts[prompt_name]
# Set up a shell expect to check whether we're still in a shell later.
self.shell_expect = self.default_expect
# Split the local prompt into two parts and separate with quotes to protect against the expect matching the command rather than the output.
self.send(ShutItSendSpec(self,
send=""" PS1='""" + shutit.expect_prompts[prompt_name][:2] + "''" + shutit.expect_prompts[prompt_name][2:] + """'""",
echo=False,
loglevel=loglevel,
ignore_background=True))
# Set up history the way shutit likes it.
self.send(ShutItSendSpec(self,
send=' command export HISTCONTROL=$HISTCONTROL:ignoredups:ignorespace',
echo=False,
loglevel=loglevel,
ignore_background=True))
# Ensure environment is set up OK.
_ = self.init_pexpect_session_environment(prefix)
return True
def revert_prompt(self,
old_prompt_name,
new_expect=None):
"""Reverts the prompt to the previous value (passed-in).
It should be fairly rare to need this. Most of the time you would just
exit a subshell rather than resetting the prompt.
- old_prompt_name -
- new_expect -
- child - See send()
"""
shutit = self.shutit
expect = new_expect or self.default_expect
# v the space is intentional, to avoid polluting bash history.
self.send(ShutItSendSpec(self,
send=(' PS1="${PS1_%s}" && unset PS1_%s') % (old_prompt_name, old_prompt_name),
expect=expect,
check_exit=False,
fail_on_empty_before=False,
echo=False,
loglevel=logging.DEBUG,
ignore_background=True))
if not new_expect:
shutit.log('Resetting default expect to default', level=logging.DEBUG)
shutit.set_default_shutit_pexpect_session_expect()
_ = self.init_pexpect_session_environment(old_prompt_name)
def expect(self,
expect,
searchwindowsize=None,
maxread=None,
timeout=None,
iteration_n=1):
"""Handle child expects, with EOF and TIMEOUT handled
iteration_n - Number of times this expect has been called for the send.
If 1, (the default) then it gets added to the pane of output
(if applicable to this run)
"""
if isinstance(expect, str):
expect = [expect]
if searchwindowsize != None:
old_searchwindowsize = self.pexpect_child.searchwindowsize
self.pexpect_child.searchwindowsize = searchwindowsize
if maxread != None:
old_maxread = self.pexpect_child.maxread
self.pexpect_child.maxread = maxread
res = self.pexpect_child.expect(expect + [pexpect.TIMEOUT] + [pexpect.EOF], timeout=timeout)
if searchwindowsize != None:
self.pexpect_child.searchwindowsize = old_searchwindowsize
if maxread != None:
self.pexpect_child.maxread = old_maxread
# Add to session lines only if pane manager exists.
if shutit_global.shutit_global_object.pane_manager and iteration_n == 1:
time_seen = time.time()
lines_to_add = []
if isinstance(self.pexpect_child.before, (str,unicode)):
for line_str in self.pexpect_child.before.split('\n'):
lines_to_add.append(line_str)
if isinstance(self.pexpect_child.after, (str,unicode)):
for line_str in self.pexpect_child.after.split('\n'):
lines_to_add.append(line_str)
# If first or last line is empty, remove it.
#if len(lines_to_add) > 0 and lines_to_add[1] == '':
# lines_to_add = lines_to_add[1:]
#if len(lines_to_add) > 0 and lines_to_add[-1] == '':
# lines_to_add = lines_to_add[:-1]
for line in lines_to_add:
self.session_output_lines.append(SessionPaneLine(line_str=line, time_seen=time_seen, line_type='output'))
return res
def replace_container(self, new_target_image_name, go_home=None):
"""Replaces a container. Assumes we are in Docker context.
"""
shutit = self.shutit
shutit.log('Replacing container with ' + new_target_image_name + ', please wait...', level=logging.DEBUG)
shutit.log(shutit.print_session_state(), level=logging.DEBUG)
# Destroy existing container.
conn_module = None
for mod in shutit.conn_modules:
if mod.module_id == shutit.build['conn_module']:
conn_module = mod
break
if conn_module is None:
shutit.fail('''Couldn't find conn_module ''' + shutit.build['conn_module']) # pragma: no cover
container_id = shutit.target['container_id']
conn_module.destroy_container(shutit, 'host_child', 'target_child', container_id)
# Start up a new container.
shutit.target['docker_image'] = new_target_image_name
target_child = conn_module.start_container(shutit, self.pexpect_session_id)
conn_module.setup_target_child(shutit, target_child)
shutit.log('Container replaced', level=logging.DEBUG)
shutit.log(shutit.print_session_state(), level=logging.DEBUG)
# New session - log in. This makes the assumption that we are nested
# the same level in in terms of shells (root shell + 1 new login shell).
target_child = shutit.get_shutit_pexpect_session_from_id('target_child')
if go_home != None:
target_child.login(ShutItSendSpec(self,
send=shutit_global.shutit_global_object.bash_startup_command,
check_exit=False,
echo=False,
go_home=go_home))
else:
target_child.login(ShutItSendSpec(self,
send=shutit_global.shutit_global_object.bash_startup_command,
check_exit=False,
echo=False))
return True
def whoami(self,
note=None,
loglevel=logging.DEBUG):
"""Returns the current user by executing "whoami".
@param note: See send()
@return: the output of "whoami"
@rtype: string
"""
shutit = self.shutit
shutit.handle_note(note)
res = self.send_and_get_output(' command whoami',
echo=False,
loglevel=loglevel).strip()
if res == '':
res = self.send_and_get_output(' command id -u -n',
echo=False,
loglevel=loglevel).strip()
shutit.handle_note_after(note=note)
return res
def check_last_exit_values(self,
send,
check_exit=True,
expect=None,
exit_values=None,
retry=0,
retbool=False):
"""Internal function to check the exit value of the shell. Do not use.
"""
shutit = self.shutit
expect = expect or self.default_expect
if not self.check_exit or not check_exit:
shutit.log('check_exit configured off, returning', level=logging.DEBUG)
return True
if exit_values is None:
exit_values = ['0']
if isinstance(exit_values, int):
exit_values = [str(exit_values)]
# Don't use send here (will mess up last_output)!
# Space before "echo" here is sic - we don't need this to show up in bash history
send_exit_code = ' echo EXIT_CODE:$?'
shutit.log('Sending with sendline: ' + str(send_exit_code), level=logging.DEBUG)
assert not self.sendline(ShutItSendSpec(self,
send=send_exit_code,
ignore_background=True)), shutit_util.print_debug()
shutit.log('Expecting: ' + str(expect), level=logging.DEBUG)
self.expect(expect,timeout=10)
shutit.log('before: ' + str(self.pexpect_child.before), level=logging.DEBUG)
res = shutit.match_string(str(self.pexpect_child.before), '^EXIT_CODE:([0-9][0-9]?[0-9]?)$')
if res not in exit_values or res is None: # pragma: no cover
res_str = res or str(res)
shutit.log('shutit_pexpect_child.after: ' + str(self.pexpect_child.after), level=logging.DEBUG)
shutit.log('Exit value from command: ' + str(send) + ' was:' + res_str, level=logging.DEBUG)
msg = ('\nWARNING: command:\n' + send + '\nreturned unaccepted exit code: ' + res_str + '\nIf this is expected, pass in check_exit=False or an exit_values array into the send function call.')
shutit.build['report'] += msg
if retbool:
return False
elif retry == 1 and shutit_global.shutit_global_object.interactive >= 1:
# This is a failure, so we pass in level=0
shutit.pause_point(msg + '\n\nInteractive, so not retrying.\nPause point on exit_code != 0 (' + res_str + '). CTRL-C to quit', shutit_pexpect_child=self.pexpect_child, level=0)
elif retry == 1:
shutit.fail('Exit value from command\n' + send + '\nwas:\n' + res_str, throw_exception=False) # pragma: no cover
else:
return False
return True
def pause_point(self,
msg='SHUTIT PAUSE POINT',
print_input=True,
resize=True,
color='32',
default_msg=None,
interact=False,
wait=-1):
"""Inserts a pause in the build session, which allows the user to try
things out before continuing. Ignored if we are not in an interactive
mode.
Designed to help debug the build, or drop to on failure so the
situation can be debugged.
@param msg: Message to display to user on pause point.
@param print_input: Whether to take input at this point (i.e. interact), or
simply pause pending any input.
Default: True
@param resize: If True, try to resize terminal.
Default: False
@param color: Color to print message (typically 31 for red, 32 for green)
@param default_msg: Whether to print the standard blurb
@param interact: Interact without mediation, and set up environment.
@param wait: Wait a few seconds rather than for input (for video mode)
@type msg: string
@type print_input: boolean
@type resize: boolean
@type wait: decimal
@return: True if pause point handled ok, else false
"""
shutit = self.shutit
# Try and stop user being 'clever' if we are in an exam and not in debug
if shutit.build['exam'] and shutit.loglevel not in ('DEBUG',):
self.send(ShutItSendSpec(self,
send=' command alias exit=/bin/true && command alias logout=/bin/true && command alias kill=/bin/true && command alias alias=/bin/true',
echo=False,
record_command=False,
ignore_background=True))
# Flush history before we 'exit' the current session.
# THIS CAUSES BUGS IF WE ARE NOT IN A SHELL... COMMENTING OUT
# IF THE DEFAULT PEXPECT == THE CURRENCT EXPECTED, THEN OK, gnuplot in shutit-scripts with walkthrough=True is a good test
# Errors seen when check_exit=True
if self.in_shell:
self.send(ShutItSendSpec(self,
send=' set +m && { : $(history -a) & } 2>/dev/null',
check_exit=False,
echo=False,
record_command=False,
ignore_background=True))
if print_input:
# Do not resize if we are in video mode (ie wait > 0)
if resize and wait < 0:
# It is possible we do not have distro set yet, so wrap in try/catch
try:
assert not self.sendline(ShutItSendSpec(self,
send='',
echo=False,
ignore_background=True)), shutit_util.print_debug()
except Exception:
pass
if default_msg is None:
if not shutit.build['video'] and not shutit.build['training'] and not shutit.build['exam'] and not shutit.build['walkthrough'] and self.shutit.loglevel not in ('DEBUG',):
pp_msg = '\r\nYou now have a standard shell.'
if not interact:
pp_msg += '\r\nHit CTRL and then ] at the same time to continue ShutIt run, CTRL-q to quit.'
if shutit.build['delivery'] == 'docker':
pp_msg += '\r\nHit CTRL and u to save the state to a docker image'
shutit.log(shutit_util.colorise(color,'\r\n' + 80*'=' + '\r\n' + msg + '\r\n' + 80*'='+'\r\n' + pp_msg),transient=True, level=logging.CRITICAL)
else:
shutit.log('\r\n' + (shutit_util.colorise(color, msg)),transient=True, level=logging.critical)
else:
shutit.log(shutit_util.colorise(color, msg) + '\r\n' + default_msg + '\r\n',transient=True, level=logging.CRITICAL)
oldlog = self.pexpect_child.logfile
self.pexpect_child.logfile = None
if wait > 0:
time.sleep(wait)
else:
# Re-set the window size to match the original window.
# TODO: sigwinch. Line assumes no change.
self.pexpect_child.setwinsize(shutit_global.shutit_global_object.root_window_size[0],shutit_global.shutit_global_object.root_window_size[1])
# TODO: handle exams better?
self.expect('.*')
if not shutit.build['exam'] and self.shutit.loglevel not in ('DEBUG',):
if self.in_shell:
# Give them a 'normal' shell.
assert not self.sendline(ShutItSendSpec(self,
send=' bash',
echo=False,
ignore_background=True)), shutit_util.print_debug()
self.expect('.*')
else:
shutit.log('Cannot create subshell, as not in a shell.', level=logging.DEBUG)
if interact:
self.pexpect_child.interact()
try:
#shutit_global.shutit_global_object.shutit_print('pre interact')
if shutit_global.shutit_global_object.ispy3:
# For some reason interact barfs when we use _pause_input_filter, so drop it for PY3: https://github.com/pexpect/pexpect/blob/master/pexpect/pty_spawn.py#L819
self.pexpect_child.interact()
else:
self.pexpect_child.interact(input_filter=self._pause_input_filter)
#shutit_global.shutit_global_object.shutit_print('post interact')
self.handle_pause_point_signals()
#shutit_global.shutit_global_object.shutit_print('post handle_pause_point_signals')
except Exception as e:
shutit.fail('Terminating ShutIt within pause point.\r\n' + str(e)) # pragma: no cover
if not shutit.build['exam'] and self.shutit.loglevel not in ('DEBUG',):
if self.in_shell:
assert not self.send(ShutItSendSpec(self,
send=' exit',
check_exit=False,
echo=False,
ignore_background=True)), shutit_util.print_debug()
else:
shutit.log('Cannot exit as not in shell', level=logging.DEBUG)
self.pexpect_child.logfile = oldlog
else:
pass
shutit.build['ctrlc_stop'] = False
return True
def handle_pause_point_signals(self):
shutit = self.shutit
#shutit_global.shutit_global_object.shutit_print('in handle_pause_point_signals, signal_id: ' + str(shutit_global.shutit_global_object.signal_id))
if shutit_global.shutit_global_object.signal_id == 29:
shutit.log('\r\nCTRL-] caught, continuing with run...', level=logging.INFO,transient=True)
elif isinstance(shutit_global.shutit_global_object.signal_id, int) and shutit_global.shutit_global_object.signal_id not in (0,4,7,8,17,19):
shutit.log('\r\nLeaving interact without CTRL-] and shutit_signal is not recognised, shutit_signal value: ' + str(shutit_global.shutit_global_object.signal_id), level=logging.CRITICAL,transient=True)
elif shutit_global.shutit_global_object.signal_id == 0:
shutit.log('\r\nLeaving interact without CTRL-], assuming exit.', level=logging.CRITICAL,transient=True)
shutit_global.shutit_global_object.handle_exit(exit_code=1)
if shutit.build['exam'] and self.shutit.loglevel not in ('DEBUG',):
self.send(ShutItSendSpec(self,
send=' unalias exit && unalias logout && unalias kill && unalias alias',
echo=False,
record_command=False,
ignore_background=True))
return True
def file_exists(self,
filename,
directory=False,
note=None,
loglevel=logging.DEBUG):
"""Return True if file exists on the target host, else False
@param filename: Filename to determine the existence of.
@param directory: Indicate that the file is a directory.
@param note: See send()
@type filename: string
@type directory: boolean
@rtype: boolean
"""
shutit = self.shutit
shutit.handle_note(note, 'Looking for filename in current environment: ' + filename)
test_type = '-d' if directory is True else '-e' if directory is None else '-a'
# v the space is intentional, to avoid polluting bash history.
test = ' test %s %s' % (test_type, filename)
output = self.send_and_get_output(test + ' && echo FILEXIST-""FILFIN || echo FILNEXIST-""FILFIN',
record_command=False,
echo=False,
loglevel=loglevel)
res = shutit.match_string(output, '^(FILEXIST|FILNEXIST)-FILFIN$')
ret = False
if res == 'FILEXIST':
ret = True
elif res == 'FILNEXIST':
pass
else: # pragma: no cover
# Change to log?
shutit.log(repr('before>>>>:%s<<<< after:>>>>%s<<<<' % (self.pexpect_child.before, self.pexpect_child.after)),transient=True, level=logging.INFO)
shutit.fail('Did not see FIL(N)?EXIST in output:\n' + output)
shutit.handle_note_after(note=note)
return ret
def chdir(self,
path,
timeout=shutit_global.shutit_global_object.default_timeout,
note=None,
loglevel=logging.DEBUG):
"""How to change directory will depend on whether we are in delivery mode bash or docker.
@param path: Path to send file to.
@param timeout: Timeout on response
@param note: See send()
"""
shutit = self.shutit
shutit.handle_note(note, 'Changing to path: ' + path)
shutit.log('Changing directory to path: "' + path + '"', level=logging.DEBUG)
if shutit.build['delivery'] in ('bash','dockerfile'):
self.send(ShutItSendSpec(self,
send=' command cd "' + path + '"',
timeout=timeout,
echo=False,
loglevel=loglevel))
elif shutit.build['delivery'] in ('docker',):
os.chdir(path)
else:
shutit.fail('chdir not supported for delivery method: ' + str(shutit.build['delivery'])) # pragma: no cover
shutit.handle_note_after(note=note)
return True
def get_file_perms(self,
filename,
note=None,
loglevel=logging.DEBUG):
"""Returns the permissions of the file on the target as an octal
string triplet.
@param filename: Filename to get permissions of.
@param note: See send()
@type filename: string
@rtype: string
"""
shutit = self.shutit
shutit.handle_note(note)
cmd = ' command stat -c %a ' + filename
self.send(ShutItSendSpec(self,
send=' ' + cmd,
check_exit=False,
echo=False,
loglevel=loglevel,
ignore_background=True))
res = shutit.match_string(self.pexpect_child.before, '([0-9][0-9][0-9])')
shutit.handle_note_after(note=note)
return res
def add_to_bashrc(self,
line,
match_regexp=None,
note=None,
loglevel=logging.DEBUG):
"""Takes care of adding a line to everyone's bashrc
(/etc/bash.bashrc).
@param line: Line to add.
@param match_regexp: See add_line_to_file()
@param note: See send()
@return: See add_line_to_file()
"""
shutit = self.shutit
shutit.handle_note(note)
if not shutit_util.check_regexp(match_regexp):