Repository navigation
Expand file tree
/
Copy pathssh.py
More file actions
90 lines (73 loc) · 2.42 KB
/
Copy pathssh.py
File metadata and controls
90 lines (73 loc) · 2.42 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
86
87
88
89
90
# https://hackersandslackers.com/automate-ssh-scp-python-paramiko/
import paramiko
import json
from collections import namedtuple
def commandList(commands, client):
result = {}
# x = 0
# execute the commands
for command in commands:
print("=" * 30, command, "=" * 30)
stdin, stdout, stderr = client.exec_command(command)
r = stdout.read().decode()
err = stderr.read().decode()
if err:
print(err)
# x+=1
# result[command] = r
result["command"] = r
print(result)
return result
def bashScript(filename, client):
# read the BASH script content from the file
bash_script = open(filename).read()
# print("file: ", bash_script, client)
# execute the BASH script
stdin, stdout, stderr = client.exec_command(bash_script)
# read the standard output and print it
print(stdout.read().decode())
# print errors if there are any
err = stderr.read().decode()
# print(stdin)
# print(stdout)
# print(stderr)
if err:
print(err)
# client.close()
def connect(Server):
# initialize the SSH client
client = paramiko.SSHClient()
# add to known hosts
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
client.connect(hostname=Server.ip, username=Server.username, password=Server.password)
return client
except:
print("[!] Cannot connect to the SSH Server")
exit()
def execScript(client, script):
# commandList(["pkill apt"], client)
# commandList(["apt-get install git"], client)
bashScript(script, client)
# close the connection
def getClient(hostname, config):
str = open(config, "r").read()
dicts = json.loads(str)
print("if hostname is existing:", hostname)
for dict in dicts:
# print(dict)
Server = namedtuple("Server", dict.keys())(*dict.values())
print(Server.ip, Server.hostname, Server.os)
if Server.hostname == hostname:
# print(Server)
return connect(Server)
Exception("Server with hostname: " + hostname + " Not Exits")
def getBy(value, name, config):
str = open(config, "r").read()
dicts = json.loads(str)
for dict in dicts:
# print(dict)
Server = namedtuple("Server", dict.keys())(*dict.values())
if dict[name] == value:
return Server
Exception("Server with hostname: " + value + " Not Exits")