I try to return socket object from function, but after return
socket immediatly closes. Any help is greatly appreciated :) Thanks
def get_connection(ip, log, paswd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=log, password=paswd, timeout=100)
console = ssh.invoke_shell()
print(console)
return console
def get_version(console, host):
promt = console.recv(1000)
if '>' in str(promt):
console.send('enable\n')
console.send('P@ssw0rd\n')
console.send('terminal length 0\n')
console.send('show version\n')
time.sleep(2)
out = console.recv(5000).decode('utf-8')
system_version_finder = re.search('#show version\r\n(.+)', out)
if system_version_finder:
system_version = system_version_finder.group(1)
else:
system_version = 'Unknown'
print(host + '\s' + system_version)
def upload_config(console, file_path):
console.send('configure terminal\n')
with open(file_path, 'r') as config_file:
for line in config_file:
console.send(line)
for host in options.ip_address_list:
console = get_connection(host, options.login, options.password)
print(console)
get_version(console, host)
if options.conf_file_path:
upload_config(console, options.conf_file_path)
This is output of script:
<paramiko.Channel 0 (open) window=1024 -> <paramiko.Transport at 0x34f5e10 (cipher aes128-cbc, 128 bits) (active; 1 open channel(s))>>
<paramiko.Channel 0 (closed) -> <paramiko.Transport at 0x34f5e10 (unconnected)>>
Traceback (most recent call last):
File "llearn.py", line 65, in <module>
get_version(console, host)
File "llearn.py", line 32, in get_version
console.send('terminal length 0\n')
File "C:\Program Files (x86)\Python\lib\site-packages\paramiko-1.16.0-py3.4.egg\paramiko\channel.py", line 698, in send
File "C:\Program Files (x86)\Python\lib\site-packages\paramiko-1.16.0-py3.4.egg\paramiko\channel.py", line 1058, in _send
OSError: Socket is closed
Hmm, I think the contents of ssh
in get_connection
might be garbage collected after the function returns, because paramiko isn't holding on to it in console
.
Try:
def get_connection(ip, log, paswd):
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(ip, username=log, password=paswd, timeout=100)
console = ssh.invoke_shell()
console.keep_this = ssh
print(console)
return console
Note we're now storing a reference to ssh
on console
.
On FreeBSD, your version doesn't produce errors, but it doesn't seem to work either. Adding that line makes it work for me.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With