Execute command line on remote machine via ssh. Args: cmd: User-defined command (udf) to execute on the remote host. state_q: A queue collecting Thread exit states. ip: The ip-address of the host to run the command on. port: Port number that the host is listening
(
cmd: str,
state_q: queue.Queue,
ip: str,
port: int,
username: Optional[str] = "",
)
| 94 | |
| 95 | |
| 96 | def execute_remote( |
| 97 | cmd: str, |
| 98 | state_q: queue.Queue, |
| 99 | ip: str, |
| 100 | port: int, |
| 101 | username: Optional[str] = "", |
| 102 | ) -> Thread: |
| 103 | """Execute command line on remote machine via ssh. |
| 104 | |
| 105 | Args: |
| 106 | cmd: User-defined command (udf) to execute on the remote host. |
| 107 | state_q: A queue collecting Thread exit states. |
| 108 | ip: The ip-address of the host to run the command on. |
| 109 | port: Port number that the host is listening on. |
| 110 | thread_list: |
| 111 | username: Optional. If given, this will specify a username to use when issuing commands over SSH. |
| 112 | Useful when your infra requires you to explicitly specify a username to avoid permission issues. |
| 113 | |
| 114 | Returns: |
| 115 | thread: The Thread whose run() is to run the `cmd` on the remote host. Returns when the cmd completes |
| 116 | on the remote host. |
| 117 | """ |
| 118 | ip_prefix = "" |
| 119 | if username: |
| 120 | ip_prefix += "{username}@".format(username=username) |
| 121 | |
| 122 | # Construct ssh command that executes `cmd` on the remote host |
| 123 | ssh_cmd = "ssh -o StrictHostKeyChecking=no -p {port} {ip_prefix}{ip} '{cmd}'".format( |
| 124 | port=str(port), |
| 125 | ip_prefix=ip_prefix, |
| 126 | ip=ip, |
| 127 | cmd=cmd, |
| 128 | ) |
| 129 | |
| 130 | # thread func to run the job |
| 131 | def run(ssh_cmd, state_q): |
| 132 | try: |
| 133 | subprocess.check_call(ssh_cmd, shell=True) |
| 134 | state_q.put(0) |
| 135 | except subprocess.CalledProcessError as err: |
| 136 | print(f"Called process error {err}") |
| 137 | state_q.put(err.returncode) |
| 138 | except Exception: |
| 139 | state_q.put(-1) |
| 140 | |
| 141 | thread = Thread( |
| 142 | target=run, |
| 143 | args=( |
| 144 | ssh_cmd, |
| 145 | state_q, |
| 146 | ), |
| 147 | ) |
| 148 | thread.setDaemon(True) |
| 149 | thread.start() |
| 150 | # sleep for a while in case of ssh is rejected by peer due to busy connection |
| 151 | time.sleep(0.2) |
| 152 | return thread |
| 153 |
no test coverage detected