Аватар для Серый_Ветер
21 / 21 / 12
Регистрация: 09.01.2013
Сообщений: 456

Paramiko и python2.7 ошибка запуска

29.06.2019, 02:12. Показов 3863. Ответов 6
Метки нет (Все метки)

Студворк — интернет-сервис помощи студентам
при запуске в 2.7 версии выдает:
python2.7 porol.py
/usr/local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py:163: CryptographyDeprecationWarning: OpenSSL version 1.0.1 is no longer supported by the OpenSSL project, please upgrade. A future version of cryptography will drop support for it.
utils.CryptographyDeprecationWarning
Traceback (most recent call last):
File "porol.py", line 10, in <module>
client.connect(hostname=host, username=user, password=secret, port=port)
File "/usr/local/lib/python2.7/site-packages/paramiko/client.py", line 349, in connect
retry_on_signal(lambda: sock.connect(addr))
File "/usr/local/lib/python2.7/site-packages/paramiko/util.py", line 280, in retry_on_signal
return function()
File "/usr/local/lib/python2.7/site-packages/paramiko/client.py", line 349, in <lambda>
retry_on_signal(lambda: sock.connect(addr))
File "/usr/local/lib/python2.7/socket.py", line 228, in meth
return getattr(self._sock,name)(*args)
socket.error: [Errno 60] Operation timed out
и завершает работу.
при этом все пакеты с openssl:
Кликните здесь для просмотра всего текста
root@linworks:~/work/# pip install pyOpenSSL
/usr/local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py:163: CryptographyDeprecationWarning: OpenSSL version 1.0.1 is no longe supported by the OpenSSL project, please upgrade. A future version of cryptography will drop support for it.
utils.CryptographyDeprecationWarning
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A uture version of pip will drop support for Python 2.7.
Requirement already satisfied: pyOpenSSL in /usr/local/lib/python2.7/site-packages (19.0.0)
Requirement already satisfied: cryptography>=2.3 in /usr/local/lib/python2.7/site-packages (from pyOpenSSL) (2.7)
Requirement already satisfied: six>=1.5.2 in /usr/local/lib/python2.7/site-packages (from pyOpenSSL) (1.12.0)
Requirement already satisfied: enum34; python_version < "3" in /usr/local/lib/python2.7/site-packages (from cryptography>=2.3->pyOpenSSL) (1.1.6)
Requirement already satisfied: asn1crypto>=0.21.0 in /usr/local/lib/python2.7/site-packages (from cryptography>=2.3->pyOpenSSL) (0.24.0)
Requirement already satisfied: ipaddress; python_version < "3" in /usr/local/lib/python2.7/site-packages (from cryptography>=2.3->pyOpenSSL) (1.0.22)
Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python2.7/site-packages (from cryptography>=2.3->pyOpenSSL) (1.12.3)
Requirement already satisfied: pycparser in /usr/local/lib/python2.7/site-packages (from cffi!=1.11.3,>=1.8->cryptography>=2.3->pyOpenSSL) (2.19)

root@linworks:~/work/# pip install cryptography
/usr/local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py:163: CryptographyDeprecationWarning: OpenSSL version 1.0.1 is no longe supported by the OpenSSL project, please upgrade. A future version of cryptography will drop support for it.
utils.CryptographyDeprecationWarning
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A uture version of pip will drop support for Python 2.7.
Requirement already satisfied: cryptography in /usr/local/lib/python2.7/site-packages (2.7)
Requirement already satisfied: enum34; python_version < "3" in /usr/local/lib/python2.7/site-packages (from cryptography) (1.1.6)
Requirement already satisfied: asn1crypto>=0.21.0 in /usr/local/lib/python2.7/site-packages (from cryptography) (0.24.0)
Requirement already satisfied: ipaddress; python_version < "3" in /usr/local/lib/python2.7/site-packages (from cryptography) (1.0.22)
Requirement already satisfied: six>=1.4.1 in /usr/local/lib/python2.7/site-packages (from cryptography) (1.12.0)
Requirement already satisfied: cffi!=1.11.3,>=1.8 in /usr/local/lib/python2.7/site-packages (from cryptography) (1.12.3)
Requirement already satisfied: pycparser in /usr/local/lib/python2.7/site-packages (from cffi!=1.11.3,>=1.8->cryptography) (2.19)

root@linworks:~/work/# pip install OpenSSL
/usr/local/lib/python2.7/site-packages/cryptography/hazmat/bindings/openssl/binding.py:163: CryptographyDeprecationWarning: OpenSSL version 1.0.1 is no longe supported by the OpenSSL project, please upgrade. A future version of cryptography will drop support for it.
utils.CryptographyDeprecationWarning
DEPRECATION: Python 2.7 will reach the end of its life on January 1st, 2020. Please upgrade your Python as Python 2.7 won't be maintained after that date. A uture version of pip will drop support for Python 2.7.
Collecting OpenSSL
ERROR: Could not find a version that satisfies the requirement OpenSSL (from versions: none)
ERROR: No matching distribution found for OpenSSL


Как сию ошибку можно исправить в данной версии python?

Добавлено через 3 часа 33 минуты
решил проблему установкой paramiko 1.17.1

там она использует crypro вместо Cryptography

p.s.
подскажите со скриптом:
Python
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
 
import paramiko
import sys
import argparse
import geoip2.database
import socket
import os
reload(sys)
sys.setdefaultencoding('utf8')
off_count = 0
 
class Host:
    def __init__(self):
        self.user = None
        self.password = None
        self.ip = None
        self.port = None
        self.location = None
        self.host_access_time = 0
 
    @staticmethod
    def check_availability(ip, port):
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(2)
        try:
            connection = s.connect((ip, port))
            if connection != 0:
                print 'Адрес', ip, 'исправен:', port, "порт открыт."
                s.close()
                return True
        except socket.error:
            print 'Ошибка соединения, 22 порт не работает'
            global off_count
            off_count += 1
            return False
 
    def get_location(self, ip):
        #reader = geoip2.database.Reader('GeoLite2-Country.mmdb')
        #response = reader.country(ip)
        response = ''
        return response.country.names['en']
 
    def hosts_counter(self, input_list):
        print 'Проверка наличия файла: ', input_list.file
        for line in input_list.read_file(input_list.file):
            input_list.hosts_count += 1
        return input_list.hosts_count
 
    def check_host_data(self, line):
        print 'Проверка адреса', line[2]
        list_len = len(line)
        if list_len == 4 or list_len == 3 and line[2].find(".") > 1:
            return True
        else:
            print 'Проверьте исправность записи'
            return False
 
    def extract_host_data_from_line(self, line, check_result):
        if check_result == 4:
            self.user = line[0]
            self.password = line[1]
            self.ip = line[2]
            self.port = line[3]
        else:
            self.user = line[0]
            self.password = line[1]
            self.ip = line[2]
            self.port = 22
 
    def check_host(self, line, host):
        if self.extract_host_data_from_line(line):
            print "Повторное соединение с адресом: %s" % self.ip
            host.connect_to_host()
            return True
        else:
            return False
 
    def prepare_data_to_write(self, location_trigger):
        host_data = str(self.user) + ' ' + str(self.password) + ' ' + str(self.ip) + ' ' + str(self.port) + ' '
        if location_trigger:
            location = str(self.get_location(self.ip)) + ' '
        else:
            location = ''
        return host_data + location + '\n'
 
    def execute_command(self, client):
        stdin, stdout, stderr = client.exec_command('ls -l')
        data = stdout.read()
        if data:
            print 'Доступ получен'
            return True
 
    def connect_to_host(self):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        print 'Попытка соединения', self.ip
        try:
            client.connect(hostname=self.ip, username=self.user, password=self.password, port=self.port, timeout=2,
                           allow_agent=False, look_for_keys=False, banner_timeout=120)
            print 'Соединились'
            responce = self.execute_command(client)
            if responce:
                client.close()
                return True
            else:
                return False
        except paramiko.AuthenticationException:
            # sys.stderr.write("Exc: " + str(sys.exc_info()[0]) + "\n")
            print 'Авторизация не пройдена'
            print 'Адрес помечен как неисправный'
            sys.stderr = sys.__stderr__
            return False
        except paramiko.ssh_exception.SSHException as e:
            # sys.stderr.write("Exc: " + str(sys.exc_info()[0]) + "\n")
            print('Error reading SSH protocol banner')
            print('Host marked as bad')
            sys.stderr = sys.__stderr__
            return False
        except paramiko.ssh_exception.NoValidConnectionsError as e:
            # sys.stderr.write("Exc: " + str(sys.exc_info()[0]) + "\n")
            print('SSH transport is not ready...')
            print('Host marked as bad')
            return False
 
 
 
class List:
    def __init__(self, file):
        self.hosts_count = 0
        self.file = file
 
    def read_file(self, file):
        try:
            with open(file, 'r') as file:
                for line in file:
                    yield line.strip().split(' ')
        except IOError:
            print("can't read from file, IO error")
            exit(1)
 
    def write_file(self, file, data):
        try:
            with open(file, 'a') as file:
                file.write(data)
                self.hosts_count += 1
            return True
        except IOError:
            print("Can't write to output file, IO error")
            exit(1)
 
 
def cmd_arg_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input-file', default='ssh_nocheck.txt')
    parser.add_argument('-o', '--output-file', default='goods.txt')
    parser.add_argument('-b', '--bad-file', default='bads.txt')
    parser.add_argument('-l', '--location', action='store_true')
    return parser
 
 
def main():
    global off_count
    parser = cmd_arg_parser()
    namespace = parser.parse_args(sys.argv[1:])
    input_f = namespace.input_file
    output_f = namespace.output_file
    location_trigger = namespace.location
    output_list = List(output_f)
    input_list = List(input_f)
    host = Host()
    current_line_count = 0
    hosts_count_incoming = host.hosts_counter(input_list)
    print 'Найдено записей: ', hosts_count_incoming
    for line in input_list.read_file(input_list.file):
        current_line_count += 1
        print 'Проверяется запись:', current_line_count
        check_result = host.check_host_data(line)
        if check_result:
            host.extract_host_data_from_line(line, check_result)
            available = host.check_availability(host.ip, int(host.port))
            if available:
                # sys.stderr = os.devnull
                connection = host.connect_to_host()
                # sys.stderr = sys.__stderr__
                if connection:
                    prepare_data = host.prepare_data_to_write(location_trigger)
                    write_line = output_list.write_file(output_list.file, prepare_data)
                    if write_line:
                        print 'Адрес ', current_line_count, 'из', input_list.hosts_count, ' записан в файл как исправный'
    print 'Всего проверено:', input_list.hosts_count, 'адресов'
    print 'Не прошло: ', input_list.hosts_count - output_list.hosts_count,\
          'адресов.', 'Из них отключены: ', off_count, 'адрес. Не верный пароль на: ', \
          input_list.hosts_count - output_list.hosts_count - off_count, 'адресах'
    print 'Исправны: ', output_list.hosts_count,\
          'адресов'
 
 
if __name__ == "__main__":
    main()
нужно еще отдельный файл с записями ip адресов, к которым пароль не подошел.
parser.add_argument('-b', '--bad-file', default='bads.txt')
как это все прописать, с таким синтаксисом не знаком еще...
0
cpp_developer
Эксперт
20123 / 5690 / 1417
Регистрация: 09.04.2010
Сообщений: 22,546
Блог
29.06.2019, 02:12
Ответы с готовыми решениями:

Paramiko 1.8 и python2.7
подскажите, как запускать paramiko с ключами(не путать ключи авторизации)? соединенине с оборудованием происходит так: ssh -m...

Ошибка запуска Eclipse. Исчезает ехе файл запуска
Привет всем :P Изучаю С++ на Eclipse. Создал проект Hello World. Нажимаю Run - все хорошо. Меняю немного код , дополняю его , совсем...

Python + paramiko
Hello everybody. Получаю из БД ip адреса хостов и на них хочу получить список виртуалок. В качестве ответа получаю: Host...

6
1293 / 677 / 367
Регистрация: 07.01.2019
Сообщений: 2,302
29.06.2019, 04:17
Цитата Сообщение от Серый_Ветер Посмотреть сообщение
как это все прописать, с таким синтаксисом не знаком еще...
Все это что?
0
 Аватар для Серый_Ветер
21 / 21 / 12
Регистрация: 09.01.2013
Сообщений: 456
30.06.2019, 19:16  [ТС]
Цитата Сообщение от tooru Посмотреть сообщение
Все это что?
Цитата Сообщение от Серый_Ветер Посмотреть сообщение
отдельный файл с записями ip адресов, к которым пароль не подошел.
пока думаю.

предполагаю, что вроде как сюда вписать надо else:
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
            available = host.check_availability(host.ip, int(host.port))
            if available:
                # sys.stderr = os.devnull
                connection = host.connect_to_host()
                # sys.stderr = sys.__stderr__
            if connection:
                    prepare_data = host.prepare_data_to_write(location_trigger)
                    write_line = output_list.write_file(output_list.file, prepare_data)
                    if write_line:
                        print 'Адрес ', current_line_count, 'из', input_list.hosts_count, ' записан в файл как исправный'
                else:
                    write_line = output_list.write_file_off(output_list.file_off, prepare_data)
         :
но мне нужен только список ip адресов в этом файле.
да и else получается будет писать и отключенные ip тоже, а мне надо где подключение есть, но пароль не подошел.

Добавлено через 1 минуту
хотя, нет, не верный код, он как раз будет писать отключенные машины..

я запутался))

Добавлено через 4 часа 44 минуты
сам решил добавление в файл, но поломал при этом счетчик отключенных адресов:

Python
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
#!/usr/bin/python
# -*- coding: utf-8 -*-
 
 
import paramiko
import sys
import argparse
import geoip2.database
import socket
import os
reload(sys)
sys.setdefaultencoding('utf8')
 
class Host:
    def __init__(self):
        self.user = None
        self.password = None
        self.ip = None
        self.port = None
        self.location = None
        self.host_access_time = 0
        self.off_count = 0
 
    #@staticmethod
    def check_availability(self, ip, port):
        host = Host()
        #def __init__(self):
        #   self.off_count
        s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        s.settimeout(2)
        try:
            connection = s.connect((ip, port))
            if connection != 0:
                print 'Адрес', ip, 'исправен:', port, "порт открыт."
                s.close()
                return True
        except socket.error:
            print 'Ошибка соединения, 22 порт не работает'
            #host = Host()
            host.off_count += 1
            print host.off_count
            return False
 
    def get_location(self, ip):
        #reader = geoip2.database.Reader('GeoLite2-Country.mmdb')
        #response = reader.country(ip)
        response = ''
        return response.country.names['en']
 
    def hosts_counter(self, input_list):
        print 'Проверка наличия файла: ', input_list.file
        for line in input_list.read_file(input_list.file):
            input_list.hosts_count += 1
        return input_list.hosts_count
 
    def check_host_data(self, line):
        print 'Проверка адреса', line[2]
        list_len = len(line)
        if list_len == 4 or list_len == 3 and line[2].find(".") > 1:
            return True
        else:
            print 'Проверьте исправность записи'
            return False
 
    def extract_host_data_from_line(self, line, check_result):
        if check_result == 4:
            self.user = line[0]
            self.password = line[1]
            self.ip = line[2]
            self.port = line[3]
        else:
            self.user = line[0]
            self.password = line[1]
            self.ip = line[2]
            self.port = 22
 
    def check_host(self, line, host):
        if self.extract_host_data_from_line(line):
            print "Повторное соединение с адресом: %s" % self.ip
            host.connect_to_host()
            return True
        else:
            return False
 
    def prepare_data_to_write(self, location_trigger):
        #host_data = str(self.user) + ' ' + str(self.password) + ' ' + str(self.ip) + ' ' + str(self.port) + ' '
        host_data = str(self.user) + ' ' + str(self.password) + ' ' + str(self.ip) + ' '
        #if location_trigger:
        #    location = str(self.get_location(self.ip)) + ' '
        #else:
        #    location = ''
        location = ''
        return host_data + location + '\n'
 
    def prepare_data_bad_to_write(self, location_trigger):
        #host_data = str(self.user) + ' ' + str(self.password) + ' ' + str(self.ip) + ' ' + str(self.port) + ' '
        host_data = str(self.ip) + ' '
        #if location_trigger:
        #    location = str(self.get_location(self.ip)) + ' '
        #else:
        #    location = ''
        location = ''
        return host_data + location + '\n'
 
    def execute_command(self, client):
        stdin, stdout, stderr = client.exec_command('hostname')
        data = stdout.read()
        if data:
            print 'Доступ получен'
            return True
 
    def connect_to_host(self):
        client = paramiko.SSHClient()
        client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        print 'Попытка соединения с', self.ip
        try:
            client.connect(hostname=self.ip, username=self.user, password=self.password, port=self.port, timeout=2,
                           allow_agent=False, look_for_keys=False, banner_timeout=120)
            print 'Соединились'
            responce = self.execute_command(client)
            if responce:
                client.close()
                return True
            else:
                return False
        except paramiko.AuthenticationException:
            # sys.stderr.write("Exc: " + str(sys.exc_info()[0]) + "\n")
            print 'Авторизация не пройдена'
            print 'Адрес помечен как неисправный'
            sys.stderr = sys.__stderr__
            return False
        except paramiko.ssh_exception.SSHException as e:
            # sys.stderr.write("Exc: " + str(sys.exc_info()[0]) + "\n")
            print('Error reading SSH protocol banner')
            print('Host marked as bad')
            sys.stderr = sys.__stderr__
            return False
        except paramiko.ssh_exception.NoValidConnectionsError as e:
            # sys.stderr.write("Exc: " + str(sys.exc_info()[0]) + "\n")
            print('SSH transport is not ready...')
            print('Host marked as bad')
            return False
 
 
 
class List:
    def __init__(self, file):
        self.hosts_count = 0
        self.file = file
 
    def read_file(self, file):
        try:
            with open(file, 'r') as file:
                for line in file:
                    yield line.strip().split(' ')
        except IOError:
            print("can't read from file, IO error")
            exit(1)
 
    def write_file(self, file, data):
        try:
            with open(file, 'a') as file:
                file.write(data)
                self.hosts_count += 1
            return True
        except IOError:
            print("Can't write to output file, IO error")
            exit(1)
 
 
def cmd_arg_parser():
    parser = argparse.ArgumentParser()
    parser.add_argument('-i', '--input-file', default='preout/spisok_in.txt')
    parser.add_argument('-o', '--output-file', default='preout/spikok_gods.txt')
    parser.add_argument('-b', '--bad-file', default='preout/spisok_bads.txt')
    parser.add_argument('-l', '--location', action='store_true')
    return parser
 
 
def main():
    parser = cmd_arg_parser()
    namespace = parser.parse_args(sys.argv[1:])
    input_f = namespace.input_file
    output_f = namespace.output_file
    output_bad_f = namespace.bad_file
    location_trigger = namespace.location
    output_list = List(output_f)
    output_bad= List(output_bad_f)
    input_list = List(input_f)
    host = Host()
    current_line_count = 0
    hosts_count_incoming = host.hosts_counter(input_list)
    print 'Найдено записей: ', hosts_count_incoming
    for line in input_list.read_file(input_list.file):
        current_line_count += 1
        print 'Проверяется запись:', current_line_count
        check_result = host.check_host_data(line)
        if check_result:
            host.extract_host_data_from_line(line, check_result)
            available = host.check_availability(host.ip, int(host.port))
            if available:
                # sys.stderr = os.devnull
                connection = host.connect_to_host()
                # sys.stderr = sys.__stderr__
                if connection:
                    prepare_data = host.prepare_data_to_write(location_trigger)
                    write_line = output_list.write_file(output_list.file, prepare_data)
                    if write_line:
                        print 'Адрес ', current_line_count, 'из', input_list.hosts_count, ' записан в файл как исправный'
                else:
                    prepare_data = host.prepare_data_bad_to_write(location_trigger)
                    write_line = output_bad.write_file(output_bad.file, prepare_data)
    print 'Всего проверено:', input_list.hosts_count, 'адресов'
    print 'Не прошло: ', input_list.hosts_count - output_list.hosts_count,\
          'адресов.', 'Из них отключены: ', host.off_count, 'адрес. Не верный пароль на: ', \
          input_list.hosts_count - output_list.hosts_count - host.off_count, 'адресах'
    print 'Исправны: ', output_list.hosts_count,\
          'адресов'
 
 
if __name__ == "__main__":
    main()
почему то в одной секции def счетчик host.off_count работает, а в другой показывает 0.
0
1293 / 677 / 367
Регистрация: 07.01.2019
Сообщений: 2,302
30.06.2019, 19:48
А где эти секции?
0
 Аватар для Серый_Ветер
21 / 21 / 12
Регистрация: 09.01.2013
Сообщений: 456
30.06.2019, 21:10  [ТС]
Цитата Сообщение от tooru Посмотреть сообщение
А где эти секции?
тут
Python
1
2
3
4
5
6
        except socket.error:
            print 'Ошибка соединения, 22 порт не работает'
            #host = Host()
            host.off_count += 1
            print host.off_count
            return False
все время host.off_count равно 1.
а тут:
Python
1
2
3
print 'Не прошло: ', input_list.hosts_count - output_list.hosts_count,\
          'адресов.', 'Из них отключены: ', host.off_count, 'адрес. Не верный пароль на: ', \
          input_list.hosts_count - output_list.hosts_count - host.off_count, 'адресах'
все время host.off_count равно 0

Добавлено через 1 час 19 минут
надо было всего лишь поменять host на self

Python
1
2
3
4
5
            print 'Ошибка соединения, 22 порт не работает'
            #host = Host()
            self.off_count += 1
            #print self.off_count
            return False
все работает.
0
 Аватар для Серый_Ветер
21 / 21 / 12
Регистрация: 09.01.2013
Сообщений: 456
02.07.2019, 23:16  [ТС]
Подскажите, как переделать эту функцию, под разные ответы от машин.


Python
1
2
3
4
5
6
    def execute_command(self, client):
        stdin, stdout, stderr = client.exec_command('ls -l')
        data = stdout.read()
        if data:
            print 'Доступ получен'
            return True
а то не везде есть ls-l, hostname, host, uptime....

Добавлено через 3 часа 2 минуты
2. как обработать секции:
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
        except paramiko.AuthenticationException:
            # sys.stderr.write("Exc: " + str(sys.exc_info()[0]) + "\n")
            print 'Авторизация не пройдена'
            print 'Адрес помечен как неисправный'
            sys.stderr = sys.__stderr__
            return False
        except paramiko.ssh_exception.SSHException as e:
            # sys.stderr.write("Exc: " + str(sys.exc_info()[0]) + "\n")
            print('Error reading SSH protocol banner')
            print('Host marked as bad')
            sys.stderr = sys.__stderr__
            return False
        except paramiko.ssh_exception.NoValidConnectionsError as e:
            # sys.stderr.write("Exc: " + str(sys.exc_info()[0]) + "\n")
            print('SSH transport is not ready...')
            print('Host marked as bad')
            return False
так чтобы данные вносились в spisok_bads.txt.
а то и вроде и подключение есть, но тем не менее не попадает в условия:
Python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
        if check_result:
            host.extract_host_data_from_line(line, check_result)
            available = host.check_availability(host.ip, int(host.port))
            if available:
                # sys.stderr = os.devnull
                connection = host.connect_to_host()
                # sys.stderr = sys.__stderr__
                if connection:
                    prepare_data = host.prepare_data_to_write(location_trigger)
                    write_line = output_list.write_file(output_list.file, prepare_data)
                    if write_line:
                        print 'Адрес ', current_line_count, 'из', input_list.hosts_count, ' записан в файл как исправный'
                else:
                    prepare_data = host.prepare_data_bad_to_write(location_trigger)
                    write_line = output_bad.write_file(output_bad.file, prepare_data)
0
 Аватар для Серый_Ветер
21 / 21 / 12
Регистрация: 09.01.2013
Сообщений: 456
28.07.2019, 15:25  [ТС]
Подскажите с доработкой скрипта вышеуказанного скрипта...

Есть из всего списка spisok_in.txt небольшой список ip адресов, заканчивающийся на .1 (граничный маршрутизатор)
из всего этого списка, допустим 90 адресов подключаются нормально ssh username@15.12.12.1,
а есть адреса, около 35, которые подключаются с определенными ключами ssh -m hmac-md5 -c aes-sha256 username@15.12.16.1 и по другому к ним не подключится.
Подскажите, как переделать функцию, чтобы она проверяла, если не работает первый вариант, пробовала подключение по второму, который с ключами.
0
Надоела реклама? Зарегистрируйтесь и она исчезнет полностью.
raxper
Эксперт
30234 / 6612 / 1498
Регистрация: 28.12.2010
Сообщений: 21,154
Блог
28.07.2019, 15:25
Помогаю со студенческими работами здесь

Paramiko раскрасить лог
Добрый день! Пытаюсь раскрасить вывод команды лога из &quot;paramiko&quot;: command = &quot;&quot;&quot;zcat /var/log/log-&quot;&quot;&quot;|grep -a...

Django + Paramiko SFTP
Доброго времени суток создаю небольшое решение для прослушивания аудио записей с сервера SFTP Создал конструкцию получающею пути всех...

Paramiko и вложенная SSH сессия
Здравствуйте. Решаю задачку по автоматизации рутиных задач при работе с сетевыми устройствами, а именно ввод однотипных команд на...

Paramiko экранирование спец символов в логине
Добрый день! Подскажите, как правильно экранировать спецсимволы в логине при подключении к серверу по SSH: эту строку парамико не...

Зависание инициализации окна Tkinter + Paramiko
Добрый день. Столкнулся с такой проблемой. Через по SSH делаю подключение и выполняю команду &quot;tailf test.log&quot; Далее...


Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:
7
Ответ Создать тему
Опции темы

Новые блоги и статьи
Ритм жизни
kumehtar 27.02.2026
Иногда приходится жить в ритме, где дел становится всё больше, а вовлечения в происходящее — всё меньше. Плотный график не даёт вниманию закрепиться ни на одном событии. Утро начинается с быстрых,. . .
SDL3 для Web (WebAssembly): Сборка SDL3 из исходников с помощью CMake и Emscripten
8Observer8 27.02.2026
Недавно вышла версия 3. 4. 2 библиотеки SDL3. На странице официальной релиза доступны исходники, готовые DLL (для x86, x64, arm64), а также библиотеки для разработки под Android, MinGW и Visual Studio. . . .
SDL3 для Web (WebAssembly): Реализация движения на Box2D v3 - трение и коллизии с повёрнутыми стенами
8Observer8 20.02.2026
Содержание блога Box2D позволяет легко создать главного героя, который не проходит сквозь стены и перемещается с заданным трением о препятствия, которые можно располагать под углом, как верхнее. . .
Конвертировать закладки radiotray-ng в m3u-плейлист
damix 19.02.2026
Это можно сделать скриптом для PowerShell. Использование . \СonvertRadiotrayToM3U. ps1 <path_to_bookmarks. json> Рядом с файлом bookmarks. json появится файл bookmarks. m3u с результатом. # Check if. . .
Семь CDC на одном интерфейсе: 5 U[S]ARTов, 1 CAN и 1 SSI
Eddy_Em 18.02.2026
Постепенно допиливаю свою "многоинтерфейсную плату". Выглядит вот так: https:/ / www. cyberforum. ru/ blog_attachment. php?attachmentid=11617&stc=1&d=1771445347 Основана на STM32F303RBT6. На борту пять. . .
Камера Toupcam IUA500KMA
Eddy_Em 12.02.2026
Т. к. у всяких "хикроботов" слишком уж мелкий пиксель, для подсмотра в ESPriF они вообще плохо годятся: уже 14 величину можно рассмотреть еле-еле лишь на экспозициях под 3 секунды (а то и больше),. . .
И ясному Солнцу
zbw 12.02.2026
И ясному Солнцу, и светлой Луне. В мире покоя нет и люди не могут жить в тишине. А жить им немного лет.
«Знание-Сила»
zbw 12.02.2026
«Знание-Сила» «Время-Деньги» «Деньги -Пуля»
КиберФорум - форум программистов, компьютерный форум, программирование
Powered by vBulletin
Copyright ©2000 - 2026, CyberForum.ru