从函数返回控制台对象后,paramiko/ Socket关闭



我尝试从函数返回套接字对象,但return套接字立即关闭后。任何帮助都非常感谢:)谢谢

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('enablen')
        console.send('P@ssw0rdn')
    console.send('terminal length 0n')
    console.send('show versionn')
    time.sleep(2)
    out = console.recv(5000).decode('utf-8')
    system_version_finder = re.search('#show versionrn(.+)', 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 terminaln')
    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)
这是脚本的输出:
<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 0n')
  File "C:Program Files (x86)Pythonlibsite-packagesparamiko-1.16.0-py3.4.eggparamikochannel.py", line 698, in send
  File "C:Program Files (x86)Pythonlibsite-packagesparamiko-1.16.0-py3.4.eggparamikochannel.py", line 1058, in _send
OSError: Socket is closed

嗯,我认为get_connectionssh的内容可能在函数返回后被垃圾收集,因为paramiko在console中没有坚持它。

试题:

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

注意,我们现在将ssh的引用存储在console上。

在FreeBSD上,你的版本不会产生错误,但它似乎也不起作用。加上这一行就行了

最新更新