SSH和TELNET同时使用Socket

时间:2018-02-22 14:48:41

标签: python cisco

我尝试在Python上制作一个能够通过TELNET或SSH在思科设备上访问的脚本。

代码:

import socket
from netmiko import ConnectHandler
from getpass import getpass

remote_host = raw_input("Enter IP Address: ")

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    if socket.connect_ex((remote_host, 23)) == 0:
       print 'Connection stablished via TELNET'
       device
       net_connect = ConnectHandler(**device)
       socket.close()
    elif socket.connect_ex((remote_host, 22)) == 0:
         print 'Connection stablished via SSH'
         device
         net_connect = ConnectHandler(**device)
         socket.close()
    else:
         print 'Unable to stablish the connection'
         socket.close()

username = raw_input("Enter Username: ")

device = {
    'device_type': 'cisco_ios',
    'ip': remote_host,
    'username': username,
    'password': getpass(),
}

我做错了什么? (我是Python的新手,对不起)。

非常感谢你的帮助和时间。

1 个答案:

答案 0 :(得分:1)

查看代码后。最后我可以解决它!。

让我与您分享:

remote_host = raw_input("Enter IP Address: ")
device = {}

socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if socket.connect_ex((remote_host, 23)) == 0:
    print 'Connection stablished via TELNET'
    device['device_type'] = 'cisco_ios_telnet'
    device['ip'] = remote_host
    device['username'] = raw_input("Enter Username: ")
    device['password'] = getpass()
    net_connect = ConnectHandler(**device)
    socket.close()
elif socket.connect_ex((remote_host, 22)) == 0:
    print 'Connection stablished via SSH'
    device['device_type'] = 'cisco_ios_ssh'
    device['ip'] = remote_host
    device['username'] = raw_input("Enter Username: ")
    device['password'] = getpass()
    net_connect = ConnectHandler(**device)
    socket.close()
else:
    print 'Unable to connect'
    socket.close()
    net_connect.disconnect()