python ssh paramiko保存到文件

时间:2018-05-21 10:15:39

标签: python ssh

我想保存到ssh连接的所有输出文件。 ssh连接工作正常,输出对于标准输出也是正常的。我想为文件中的每个连接创建一个文件。我已将输出行更改为下面的行,并将其移到

之上
output_filename = ip_address + ".txt"
file = open(output_filename, 'w')
file.write(output.decode)
file.close()

缺少什么?

我收到此错误:

line 100, in fractal
    except 10060:
TypeError: catching classes that do not inherit from BaseException is not allowed

它只是不保存输出。文件已创建,但为空白。

import socket
import paramiko
import time
import sys

def fractal(ip, username, passwd, enapass, command, command2, command3, command4, devtype):

    ip_address = ip
    user = username
    password = passwd
    enapw = enapass
    commando = command
    commando2 = command2
    commando3 = command3
    commando4 = command4
    devtype = devtype
    print("Connecting to: "+ip + " on Port 22")
    try:
        if ip:
            global ssh_client
            ssh_client = paramiko.client.SSHClient()
            ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
            ssh_client.connect(hostname=ip_address, username=user, password=password, compress=True, look_for_keys=False, allow_agent=False, timeout=5)


            print("##########################  CONNECTED TO: "+ip_address +"  ##########################")

            remote_connection = ssh_client.invoke_shell()
            if devtype == 'CISCO':
                results = remote_connection.send("term len 0\n")
                print(results)
                time.sleep(2)
                results = remote_connection.send("show run\n")
                print(results)
                time.sleep(6)

            if devtype == 'F5':
                remote_connection.send("term len 0\n")
                time.sleep(2)
                remote_connection.send("sh ver\n")
                time.sleep(6)
            if devtype == 'LINUX':
                remote_connection.send("pwd\n")
                time.sleep(2)
            else:
                #print("Please set IP Address first!!!")
                pass
            if enapass:
                remote_connection.send("enable\n")
                # remote_connection.send("conf t\n")
                remote_connection.send(enapw)
                remote_connection.send("\n")
            else:
                pass
            if command:
                #remote_connection.send("show run\n")
                remote_connection.send(commando)
                remote_connection.send("\n")
            else:
                print("Command not found!")
            if command2:
                remote_connection.send(commando2)
                remote_connection.send("\n")
            else:
                pass
            if command3:
                remote_connection.send(commando3)
                remote_connection.send("\n")
            else:
                pass
            if command4:
                remote_connection.send(commando4)
                remote_connection.send("\n")
            else:
                pass
            time.sleep(1)
            output = remote_connection.recv(65535)
            print(output.decode())
            print("##########################  END OF: " + ip_address + "  ##########################")
            reader = ssh_client.connect
            ssh_client.close
            output_filename = ip_address + ".txt"
            file = open(output_filename, 'w')
            file.write(output)
            file.close()

    except TypeError:
        print('Please check your settings!')
    except UnboundLocalError:
        print('Please check IP Address!')
    except paramiko.AuthenticationException:
        print(ip+": Authentication failed, please verify your credentials.")
    except paramiko.SSHException as sshException:
        print(ip+": Unable to establish SSH connection: %s" % sshException)
    except paramiko.BadHostKeyException as badHostKeyException:
        print(ip+": Unable to verify server's host key: %s" % badHostKeyException)
    except socket.error:
        print(ip+": Couldn't connect to server. Check IP Address and Port")
        # sys.exit()
    except 10060:
        print(ip+": The host was not reachable")
    except socket.gaierror:
        print(ip+': Check IP Address')
    except 11004:
        print(ip+": The host was not reachable")
    except IOError as e:
        print("I/O error({0}): {1}".format(e.errno, e.strerror))
    except ValueError:
        print("Could not convert data to an integer.")
    except FileNotFoundError:
        print("No File was selected!")
    except:
        print("Unexpected error:", sys.exc_info()[0])
        raise
    # countErr = paramiko.AuthenticationException
    # countErr = 0
    # for countErr in countErr:
    #    count = count + 1
    # print ("Athentication failures: "+countErr)

1 个答案:

答案 0 :(得分:0)

这只发生在Python3中,因为except现在需要一个类BaseException的类。并且整数10060不是。

>>> try:
...   raise ValueError
... except 10080:
...   print('dfsdf')
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
TypeError: catching classes that do not inherit from BaseException is not allowed

因此Paramiko引发了一些其他错误,但错误处理在尝试评估except 10060语句时死亡。