Browse Source

initial commit

master
Mikhail Grebenkin 7 years ago
commit
776ecd99a1
6 changed files with 286 additions and 0 deletions
  1. +130
    -0
      SetupMinersClass.py
  2. BIN
      __pycache__/SetupMinersClass.cpython-35.pyc
  3. BIN
      __pycache__/aw_sender.cpython-35.pyc
  4. +103
    -0
      aw_sender.py
  5. +11
    -0
      config.json
  6. +42
    -0
      miner_reboot.py

+ 130
- 0
SetupMinersClass.py View File

@ -0,0 +1,130 @@
#! /usr/bin/python3
# coding=utf-8
import telnetlib
import json
import paramiko
import time
class SSHSetup:
def __init__(self, host, port, user, passwd, comlist=[]):
self.host = host
self.user = user
self.passwd = passwd
self.port = port
try:
self.client = paramiko.SSHClient()
self.client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.client.connect(hostname=self.host, port=self.port, username=self.user, password=self.passwd,
look_for_keys=False, allow_agent=False)
self.ssh = self.client.invoke_shell()
time.sleep(1)
self.ssh.recv(10000)
except Exception as exc:
raise Exception('ssh error: {}'.format(exc))
if len(comlist) > 0:
if 'exit' not in comlist:
comlist.append('exit')
self.sendall(comlist)
self.close()
def send(self, command):
self.ssh.send(command + '\n')
time.sleep(1)
self.ssh.recv(10000).decode()
def sendall(self, commlist=[]):
for command in commlist:
self.send(command)
def close(self):
self.ssh.close()
class TelnetSetup:
def __init__(self, host, port, user, passwd, comlist=[]):
self.host = host
self.port = port
self.user = user
self.passwd = passwd
try:
self.tn = telnetlib.Telnet(host, port)
except Exception as exc:
raise Exception('telnet error: {}'.format(exc))
if len(comlist) > 0:
if 'exit' not in comlist:
comlist.append('exit')
self.login()
self.sendall(comlist)
self.close()
def login(self):
self.tn.read_until(b'login:')
self.tn.write(self.user.encode('utf8') + b'\n')
self.tn.read_until(b'Password:')
self.tn.write(self.passwd.encode('utf8') + b'\n')
self.tn.read_until(self.user.encode('utf8'))
def send(self, command):
self.tn.write(command.encode('utf8') + b'\n')
self.tn.read_until(self.user.encode('utf8'))
def sendall(self, comlist=[]):
for command in comlist:
self.send(command)
def close(self):
self.tn.close()
class SetupMiner:
def __init__(self, host, conf={}, telnets=[], sshs=[]):
self.host = host
self.conf = conf
if len(telnets) == 0:
self.telnets = ["exit"]
else:
self.telnets = telnets
if len(sshs) == 0:
self.sshs = ["exit"]
else:
self.sshs = sshs
try:
TelnetSetup(self.host, self.conf['telnetport'], self.conf['telnetuser'], self.conf['telnetpass'],
self.telnets)
self.result = "telnet OK; "
except Exception as exc:
self.result = "{}; ".format(exc)
try:
SSHSetup(self.host, self.conf['sshport'], self.conf['sshuser'], conf['sshpass'], self.sshs)
self.result += '\n ssh OK'
except Exception as exc:
self.result += '\n {}; '.format(exc)
def ret_result(self):
return self.result
def read_conf():
with open('config.json') as f:
conf = json.load(f)
return conf
def main():
conf = read_conf()
minerconf = {"sshuser": conf["sshuser"],
"sshpass": conf["sshpass"],
"sshport": conf["sshport"],
"telnetuser": conf["telnetuser"],
"telnetpass": conf["telnetpass"],
"telnetport": conf["telnetport"]}
comlist = ["uname -a", "ps -A", "exit"]
s = SetupMiner('10.100.4.10', minerconf)
print(s.result)
if __name__ == '__main__':
main()

BIN
__pycache__/SetupMinersClass.cpython-35.pyc View File


BIN
__pycache__/aw_sender.cpython-35.pyc View File


+ 103
- 0
aw_sender.py View File

@ -0,0 +1,103 @@
#! /usr/bin/python3
# coding=utf-8
import requests
import json
import sys
from pyzabbix import ZabbixMetric, ZabbixSender
hostname = 'hostname1'
zabbix_server = '10.3.2.5'
aw_url = 'http://10.5.0.1:17790/api/miners'
class AwZabbix:
def __init__(self, server, url, host):
self.url = url
self.server = server
self.host = host
self.data = ''
self.mult_dict = {'G': 1000000000, 'M': 1000000, 'T': 1000000000000, 'K': 1000, 'N': 0, }
self.packet = []
self.lld_data = []
def get_data(self):
if len(self.data) == 0:
self.data = requests.get(self.url).json()
def make_packet(self):
self.get_data()
if len(self.packet) != 0:
return self.packet
total_hashrate_raw = self.data['totalHashrate5s']
if total_hashrate_raw:
hashrate_mult = self.mult_dict[total_hashrate_raw[-4:-3]]
total_hashrate = float(total_hashrate_raw[:-5].replace(',', '.')) * hashrate_mult
total_hashrate = int(total_hashrate)
self.packet.append(ZabbixMetric(self.host, 'total[hashrate]', total_hashrate))
for group in self.data['groupList']:
for miner in group['minerList']:
hashrate_raw = miner['speedInfo']['hashrate']
if hashrate_raw:
hashrate_mult = self.mult_dict[hashrate_raw[-4:-3]]
hashrate = float(hashrate_raw[:-5].replace(',', '.')) * hashrate_mult
hashrate = int(hashrate)
else:
hashrate = 0
minername = str(miner['name'])
self.packet.append(ZabbixMetric(self.host, "{}[{}]".format('hashrate', minername), hashrate))
self.packet.append(ZabbixMetric(self.host, "{}[{}]".format('ip', minername), miner['hostname']))
self.packet.append(ZabbixMetric(self.host, "{}[{}]".format('group', minername), miner['groupId']))
self.packet.append(ZabbixMetric(self.host, "{}[{}]".format('name', minername), miner['name']))
self.packet.append(ZabbixMetric(self.host, "{}[{}]".format('temp', minername),
miner['temperature'][:-3]))
self.packet.append(ZabbixMetric(self.host, "{}[{}]".format('status', minername),
miner['statusInfo']['statusDisplay']))
return self.packet
def send_packet(self):
if len(self.packet) == 0:
self.make_packet()
return ZabbixSender(self.server).send(self.packet)
def lld(self):
self.get_data()
if len(self.lld_data) != 0:
return self.lld_data
self.lld_data = {}
jdat = []
for group in self.data['groupList']:
for miner in group['minerList']:
jdat.append({"{#MINERID}": str(miner['id']),
"{#IP}": str(miner['hostname']),
"{#MINERNAME}": str(miner['name'])})
self.lld_data = {'data': jdat}
return self.lld_data
def read_conf():
with open('config.json') as f:
conf = json.load(f)
return conf
def main():
conf = read_conf()
z = AwZabbix(zabbix_server, aw_url, hostname)
if len(sys.argv) == 1:
print(json.dumps(z.lld(), indent=4, sort_keys=True))
elif len(sys.argv) == 2 and sys.argv[1] == 'send':
z.send_packet()
print(1)
elif len(sys.argv) == 2 and sys.argv[1] == 'send_debug':
print(z.send_packet())
for i in z.packet:
print(i)
else:
print('Wrong args.')
if __name__ == '__main__':
main()

+ 11
- 0
config.json View File

@ -0,0 +1,11 @@
{
"sshuser":"root",
"sshpass":"admin",
"sshport":"22",
"telnetuser":"telnetd",
"telnetpass":"admin",
"telnetport":"23",
"hostname": "hostname1",
"zabbix_server": "",
"aw_url": "http://10.5.0.1:17790/api/miners"
}

+ 42
- 0
miner_reboot.py View File

@ -0,0 +1,42 @@
#! /usr/bin/python3
# coding=utf-8
from aw_sender import AwZabbix
from SetupMinersClass import SetupMiner, read_conf
import sys
import json
def reboot_miner(miner, z, conf):
for miner_dat in z.lld()['data']:
if miner_dat["{#MINERNAME}"] == miner:
miner_ip = miner_dat['{#IP}']
print(miner_ip)
s = SetupMiner(miner_ip, conf=conf, telnets=['shutdown -r now'], sshs=['shutdown -r now'])
print(s.result)
break
def main():
conf = read_conf()
print(conf)
zabbix_server = conf["zabbix_server"]
aw_url = conf["aw_url"]
hostname = conf["hostname"]
minerconf = {"sshuser": conf["sshuser"],
"sshpass": conf["sshpass"],
"sshport": conf["sshport"],
"telnetuser": conf["telnetuser"],
"telnetpass": conf["telnetpass"],
"telnetport": conf["telnetport"]}
z = AwZabbix(zabbix_server, aw_url, hostname)
if len(sys.argv) == 1:
print('Need miner name to reboot as arg')
elif len(sys.argv) == 2 and sys.argv[1] == 'test':
print(z.lld())
elif len(sys.argv) == 2:
print(reboot_miner(sys.argv[1], z, minerconf))
if __name__ == '__main__':
main()

Loading…
Cancel
Save

Powered by TurnKey Linux.