-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathssh_one.py
More file actions
85 lines (70 loc) · 1.91 KB
/
ssh_one.py
File metadata and controls
85 lines (70 loc) · 1.91 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
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
import paramiko
def run_ssh_command(
host,
username,
password=None,
key_file=None,
command="hostname",
port=22,
timeout=10
):
"""
Connect to a remote VM over SSH and run a command.
Args:
host (str): VM IP or hostname
username (str): SSH username
password (str): SSH password (optional)
key_file (str): Path to private key file (optional)
command (str): Command to execute
port (int): SSH port
timeout (int): Connection timeout
Returns:
dict: {
"host": host,
"stdout": stdout,
"stderr": stderr,
"status": exit_code
}
"""
client = paramiko.SSHClient()
# Auto accept unknown host keys
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
# Authentication
if key_file:
private_key = paramiko.RSAKey.from_private_key_file(key_file)
client.connect(
hostname=host,
port=port,
username=username,
pkey=private_key,
timeout=timeout
)
else:
client.connect(
hostname=host,
port=port,
username=username,
password=password,
timeout=timeout
)
# Run command
stdin, stdout, stderr = client.exec_command(command)
output = stdout.read().decode()
error = stderr.read().decode()
exit_code = stdout.channel.recv_exit_status()
return {
"host": host,
"stdout": output.strip(),
"stderr": error.strip(),
"status": exit_code
}
except Exception as e:
return {
"host": host,
"stdout": "",
"stderr": str(e),
"status": -1
}
finally:
client.close()