I'm not a programmer, but would like to use Python for automation of some Administrative purposes. The first application after "Hello world" I tried to create is interactive ssh client. I've read some documentation and articles and decided it would be the easiest way to use paramiko module, but unfortunately I'm facing a problem: My applications asks you to enter some neccessary information such as server ip, username, password. After this it establishes connection with defined server and provide you with cli on your screen. For emulating the process of entering command I use while loop. Unfortunately my application works well only with the first command you enter. While trying to type the second command an error appears:
Traceback (most recent call last):
File "C:\Python27\Tests\ssh_client.py", line 53, in <module>
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'
Code of the programm (Windows 7):
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()
I tried to delete while loop and just call commands one by one right in the code, but have the same problem (when typing the second command see the same error). It looks like I don't understand fully how paramiko module works. I tried to find information on web but unfortunately didn't find any solution.
I'd be very appreciated if somebody could tell me what I do wrong or give me a link on the similar issue where I can find a solution.
Thanks in advance for any help.