NetworkDoc.Ru В помощь системному администратору

lp13
lp13
Offline
0
Всем привет.

Я хочу автоматизировать некоторые процессы настройки сетевого оборудования в компании и решил прибегнуть к помощи python. Почитав немного материалов в интернете пришел к выводу, что самый простой способ это воспользоваться модулем paramiko для python, который как раз для этого и предназначается. Написал следующий код:


import paramiko

SERVER = raw_input('Please enter an ip address of remote host: ')
USER = raw_input('Please enter your username: ')
PASSWORD = raw_input('Please enter your password: ')

class MYSSHClient():

def __init__(self, server=SERVER, username=USER, password=PASSWORD):
self.server = server
self.username = username
self.password = password
self.connection = None
self.result = ''
self.is_error = False


def do_connect(self):
self.connection = paramiko.SSHClient()
self.connection.set_missing_host_key_policy(paramiko.AutoAddPolicy())
self.connection.connect(self.server, username=self.username, password=self.password)

def execute_command(self, command):
if command:
print command
stdin,stdout,stderr = self.connection.exec_command(command)
stdin.close()
error = str(stderr.read())
if error:
self.is_error = True
self.result = error
print 'error'
else:
self.is_error = False
self.result = str(stdout.read())
print 'no error'

print self.result


else:
print "no command was entered"

def do_close(self):
self.connection.close()

if __name__ == '__main__':
client = MYSSHClient()
client.do_connect()
while 1:
command = raw_input('cli: ')
if command == 'q': break
client.execute_command(command)
client.do_close()

Вначале вроде все обрабатывается нормально. Ввожу логин пароль, адрес хоста. Подключаюсь и выполняю первую команду, вижу результат вывода, и пока вроде все норм но как только пытаюсь выполнить вторую команду сразу вижу ошибку:

Traceback (most recent call last):
File "C:\Python27\Tests\ssh_client.py", line 53, in
client.execute_command(command)
File "C:\Python27\Tests\ssh_client.py", line 26, in execute_command
stdin,stdout,stderr = self.connection.exec_command(command)
File "C:\Python27\lib\site-packages\paramiko\client.py", line 343, in exec_command
chan.exec_command(command)
AttributeError: 'NoneType' object has no attribute 'exec_command'

Подозреваю, что после выполнения команды сессия закрывается и не может выполнить следующую вводимую команду.

Кто-нибудь может сталкивался с подобной проблемой, как это обойти? Либо может посоветуете какой-нибудь другой модуль?

Заранее спасибо за советы.

Accepted Answer

Friday, June 21 2013, 05:46 PM - #permalink
1
Как-то пробовал делать что-то подобное. Посмотрел несколько модулей в том числе и paramiko, но в итоге все получилось с модулем Exscript.

Приведу простой код, там уж дальше отредактируешь под свои задачи.

from Exscript.util.interact import read_login
from Exscript.protocols import SSH2

ip_address = raw_input('Please enter ip address of remote host: ')
account = read_login()
conn = SSH2()                       
conn.connect(ip_address)     
conn.login(account)  


while True:
    command = raw_input('cli: ')
    if command == 'q': break
    conn.execute(command)
    print conn.response



conn.send('quit\r')               
conn.close() 


В результате получится примитивный ssh клиент.
Сам модуль и описание можно взять здесь https://github.com/knipknap/exscript
The reply is currently minimized Show
Responses (0)
  • There are no replies here yet.
Your Reply
Сеть
Сеть
6 post(s)
VOIP
VOIP
4 post(s)
Loading ...

Joomla! Debug Console

Errors

Session

Profile Information

Memory Usage

Database Queries