1616# [START compute_oslogin_ssh]
1717"""
1818Example of using the OS Login API to apply public SSH keys for a service
19- account, and use that service account to execute commands on a remote
19+ account, and use that service account to run commands on a remote
2020instance over SSH. This example uses zonal DNS names to address instances
2121on the same internal VPC network.
2222"""
@@ -43,19 +43,19 @@ def execute(
4343 raise_errors : Optional [bool ] = True
4444) -> Tuple [int , str ]:
4545 """
46- Executes an external command (wrapper for Python subprocess).
46+ Run an external command (wrapper for Python subprocess).
4747
4848 Args:
49- cmd: The command to be executed .
50- cwd: Directory in which to execute the command.
49+ cmd: The command to be run .
50+ cwd: Directory in which to run the command.
5151 capture_output: Should the command output be captured and returned or just ignored.
5252 env: Environmental variables passed to the child process.
53- raise_errors: Should errors in executed command raise exceptions.
53+ raise_errors: Should errors in run command raise exceptions.
5454
5555 Returns:
5656 Return code and captured output.
5757 """
58- print (f'Executing command: { cmd } ' )
58+ print (f'Running command: { cmd } ' )
5959 process = subprocess .run (
6060 cmd ,
6161 cwd = cwd ,
@@ -126,7 +126,7 @@ def run_ssh(cmd: str, private_key_file: str, username: str, hostname: str) -> st
126126 hostname: Hostname of the machine you want to run the command on.
127127
128128 Returns:
129- Output of the executed command.
129+ Output of the run command.
130130 """
131131 ssh_command = [
132132 'ssh' ,
@@ -136,7 +136,7 @@ def run_ssh(cmd: str, private_key_file: str, username: str, hostname: str) -> st
136136 f'{ username } @{ hostname } ' ,
137137 cmd ,
138138 ]
139- print (f"Executing ssh command: { ' ' .join (ssh_command )} " )
139+ print (f"Running ssh command: { ' ' .join (ssh_command )} " )
140140 tries = 0
141141 while tries < 3 :
142142 try :
@@ -154,7 +154,10 @@ def run_ssh(cmd: str, private_key_file: str, username: str, hostname: str) -> st
154154 time .sleep (30 )
155155 tries += 1
156156 if tries == 3 :
157- print (f"Failed to execute SSH command (return code: { err .returncode } . Output received: { err .output } " )
157+ if isinstance (subprocess .CalledProcessError , err ):
158+ print (f"Failed to run SSH command (return code: { err .returncode } . Output received: { err .output } " )
159+ else :
160+ print ("Failed to run SSH - timed out." )
158161 raise err
159162 else :
160163 return ssh .stdout
0 commit comments