Найти - Пользователи
Полная версия: Глупый вопрос по поводу цикла
Начало » Python для новичков » Глупый вопрос по поводу цикла
1
kotofey
Прошу помощи в корректности состовления цикла. Почему-то туплю и не могу понять как правильно сделать.

Суть написанного ниже - при запуске собирать данные со всех серверов и записывать в файл
в списках server_ip - хост сервера, code_server - пароль. Никак не додумаю как правильно составить цикл. Надеюсь на подсказку сообщества.

server_ip = ('', '', '')
code_server = ('', '', '')
a = 0
b = 0
for x in server_ip:
    host = server_ip[a]
    print(a)
    for z in code_server:
        pwd = code_server[b]
        print(b)
    user = 'user'
    port = 22
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # Подключение
    client.connect(hostname=host, username=user, password=pwd, port=port)
    stdin, stdout, stderr = client.exec_command('uptime', get_pty=True) # добавить get_pty=True
    time.sleep(1)
        # Читаем ответ сервера
    data = stdout.read() + stderr.read()
    client.close()
    d = datetime.now()
# Записываем ответ сервера в файл
    save_changes = open('log.txt', 'ab')
    save_changes.writelines(d.strftime('time: ' + '%H:%M:%S ' + 'date: ' '%d-%m-%y'+ '\n'))
    save_changes.writelines(data)
    save_changes.close()
    b += 1
    if b <= 2:
        continue
    else:
        break
    a += 1
    if a <= 2:
        continue
    else:
        break
print('Соединение закрыто, данные записаны в файл.')
JOHN_16
Я так понял что вам нужно сопоставить хост сервера и его пароль в один проход цикла?
for host, code in zip(server_ip, code_server):
    # some code
kampella
server_ip = ('', ‘', ’')
code_server = ('', ‘', ’')

это в словарь

server_ip = ('', '', '')
code_server = ('', '', '')
hosts = dict(zip(server_ip, code_server))
    user = 'user'
    port = 22
for host, pwd in hosts.items():
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    # Подключение
    client.connect(hostname=host, username=user, password=pwd, port=port)
    stdin, stdout, stderr = client.exec_command('uptime', get_pty=True) # добавить get_pty=True
    time.sleep(1)
        # Читаем ответ сервера
    data = stdout.read() + stderr.read()
    client.close()
    d = datetime.now()
# Записываем ответ сервера в файл
    save_changes = open('log.txt', 'ab')
    save_changes.writelines(d.strftime('time: ' + '%H:%M:%S ' + 'date: ' '%d-%m-%y'+ '\n'))
    save_changes.writelines(data)
    save_changes.close()
kotofey
Спасибо за помощь!
This is a "lo-fi" version of our main content. To view the full version with more information, formatting and images, please click here.
Powered by DjangoBB