Paramiko / Socket closes after the console object returns from the function

I am trying to return a socket object from a function, but after the returnsocket closes immediately. Any help is much 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 the script output:

<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
+4
source share
1 answer

Hmm, I think that the contents sshin get_connectionmay be garbage collected after the function returns, because paramiko does not hold on to it 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

Please note that we now keep the link sshto console.

On FreeBSD, your version does not generate errors, but it also does not work. Adding this line makes it work for me.

+4
source

All Articles