1#!/usr/bin/env python 2# Copyright 2019 The Chromium Authors. All rights reserved. 3# Use of this source code is governed by a BSD-style license that can be 4# found in the LICENSE file. 5 6import base64 7import re 8import subprocess 9import sys 10 11# Usage: win_ssh_cmd.py <user@host> <cmd shell string> [<fail errorlevel>] 12# Runs the given command over ssh and exits with 0 if the command succeeds or 1 13# if the command fails. The command is considered to fail if the errorlevel is 14# greater than or equal to <fail errorlevel>. 15 16 17SENTINEL = 'win_ssh_cmd remote command successful' 18 19def main(user_host, cmd, fail_errorlevel): 20 ssh_cmd = ['ssh', '-oConnectTimeout=15', '-oBatchMode=yes', user_host, 21 '(' + cmd + ') & if not errorlevel %s echo %s' % ( 22 fail_errorlevel, SENTINEL)] 23 # True if we saw a line matching SENTINEL. 24 saw_sentinel = False 25 print >> sys.stderr, 'Original command:\n%s\nFull command:\n%s' % ( 26 cmd, ' '.join([repr(s) for s in ssh_cmd])) 27 proc = subprocess.Popen(ssh_cmd, stdout=subprocess.PIPE) 28 for line in iter(proc.stdout.readline, ''): 29 stripped = line.strip() 30 if stripped == SENTINEL: 31 saw_sentinel = True 32 else: 33 print stripped 34 proc.wait() 35 sys.stdout.flush() 36 if proc.returncode != 0: 37 sys.exit(proc.returncode) 38 if not saw_sentinel: 39 sys.exit(1) 40 sys.exit(0) 41 42 43if __name__ == '__main__': 44 if len(sys.argv) < 3: 45 print >> sys.stderr, ( 46 'USAGE: %s <user@host> <cmd shell string> [<fail errorlevel>]' % 47 sys.argv[0]) 48 sys.exit(1) 49 arg_fail_errorlevel = 1 if len(sys.argv) < 4 else sys.argv[3] 50 main(sys.argv[1], sys.argv[2], arg_fail_errorlevel) 51