coding utf-8 from work import make_work import paramiko import logging

  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
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
# -*- coding: utf-8 -*-
from work import make_work
import paramiko
import logging
import os
import time
from settings import threads, directory, accounts, good, bad, dirs
os.chdir(os.path.dirname(os.path.abspath(__file__)))
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger('paramiko.transport')
logger.setLevel(logging.ERROR)
def timer(f):
def tmp(*args, **kwargs):
t = time.time()
res = f(*args, **kwargs)
logging.info("Время выполнения функции: %f" % (time.time() - t))
return res
return tmp
class SSH(paramiko.SSHClient):
def exec_command(self, command, bufsize=-1, timeout=None):
chan = self._transport.open_session()
chan.settimeout(timeout)
chan.exec_command(command)
stdin = chan.makefile('wb', bufsize)
stdout = chan.makefile('rb', bufsize)
stderr = chan.makefile_stderr('rb', bufsize)
return stdin, stdout, stderr
def directory_exists(self, path):
command = 'if [ -d %s ] ;then echo true; else echo false; fi' % path
stdin, stdout, stderr = self.exec_command(command)
message = stdout.read().strip()
return message == "true"
class Checker(object):
def __init__(self):
self.good = open(good, "a")
self.bad = open(bad, "a")
self.dirs = open(dirs, "a")
self.directory = directory
def write_line(self, account, file_type):
message = ''
if file_type == "good":
f = self.good
message = "%s is success!" % account
elif file_type == "bad":
f = self.bad
message = "%s is bad!" % account
elif file_type == "dirs":
f = self.dirs
message = "%s directory '%s' exists" % (account, self.directory)
f.write(account + '\n')
f.flush()
logging.debug(message)
def check(self, account):
host, login, password = account.split()
ssh = SSH()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
try:
ssh.connect(host, username=login, password=password, timeout=10)
self.write_line(account, 'good')
if ssh.directory_exists(self.directory):
self.write_line(account, 'dirs')
except:
self.write_line(account, 'bad')
finally:
ssh.close()
def worker(self, account):
try:
self.check(account)
finally:
yield account
def remove_line(rmline):
with open(accounts, 'r+') as f:
tasks = [account for account in f]
for i, account in enumerate(tasks):
if account.strip() == rmline:
del tasks[i]
break
data = ''.join(tasks)
f.seek(0)
f.truncate(0)
f.write(data)
def main():
tasks = [account.strip() for account in open(accounts)]
c = Checker()
for account in make_work(c.worker, tasks, threads):
try:
pass
#remove_line(account)
except KeyboardInterrupt:
return
if __name__ == "__main__":
main()