-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathssh_client.py
More file actions
59 lines (51 loc) · 1.53 KB
/
Copy pathssh_client.py
File metadata and controls
59 lines (51 loc) · 1.53 KB
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
"""
ssh_client.py — 通过 paramiko 在远程 Linux 编译机执行命令
"""
import logging
from typing import Tuple
log = logging.getLogger("ssh")
def run_ssh_command(
host: str,
port: int,
username: str,
key_path: str,
command: str,
timeout: int = 600,
) -> Tuple[int, str, str]:
"""
在远程主机执行命令
返回 (exit_code, stdout, stderr)
"""
try:
import paramiko
except ImportError:
return (-1, "", "paramiko not installed. pip install paramiko")
try:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
if key_path:
ssh.connect(
hostname=host,
port=port,
username=username,
key_filename=key_path,
timeout=15,
)
else:
ssh.connect(
hostname=host,
port=port,
username=username,
look_for_keys=True,
timeout=15,
)
stdin, stdout, stderr = ssh.exec_command(command, timeout=timeout)
out = stdout.read().decode("utf-8", errors="replace")
err = stderr.read().decode("utf-8", errors="replace")
rc = stdout.channel.recv_exit_status()
ssh.close()
log.info(f"SSH {username}@{host}: rc={rc}, out={len(out)}B, err={len(err)}B")
return (rc, out, err)
except Exception as e:
log.error(f"SSH FAILED {username}@{host}: {e}")
return (-1, "", str(e))