Python paramiko不执行字符串

时间:2016-03-21 10:32:58

标签: python ssh paramiko

我是Python的新手,我正在尝试使用函数发送命令。我有超过1个命令发送我将它们放在带有返回的字符串中并尝试执行该字符串。到目前为止,这还没有成功。我还添加了一个打印来显示字符串。当我运行脚本时,当前不打印。

有人可以帮帮我吗? 感谢

import paramiko
import time

# For debugging only
paramiko.common.logging.basicConfig(level=paramiko.common.DEBUG)

def Send_Command_and_Get_Response(command, reponse, result):
    # Send the su command
    shell.send(command)

    # Create a new receive buffer
    receive_buffer = ""

    while not reponse in receive_buffer:
        # Flush the receive buffer
        receive_buffer += shell.recv(1024)

    # Print the receive buffer, if necessary
    if result:
        print receive_buffer

    return receive_buffer   

# VARIABLES THAT NEED CHANGED
ip = '10.xx.xx.xx'
username = 'root'
password = ''
port = 3008

# Create instance of SSHClient object
client = paramiko.SSHClient()

# Make sure that we add the remote server's SSH key automatically
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())


# initiate SSH connection
client.connect(ip, username=username, password=password,port=port, look_for_keys=False, allow_agent=False)
print "SSH connection established to %s" % ip

# Use invoke_shell to establish an 'interactive session'
shell = client.invoke_shell()


print "Interactive SSH session established"
time.sleep(1)
shell.send("ls -ltr\n")
output = shell.recv(1000)
print output


#answer no to auto config
is_auto = shell.recv(1024)
if "Would you like" in is_auto:
    Send_Command_and_Get_Response("no\n", "#", False)

# clear any config sessions
is_global = shell.recv(1024)
if ")#" in is_global:
    Send_Command_and_Get_Response("end\n", "#", False)

# if not in enable mode go to enable mode
is_enable = shell.recv(1024)
if ">" in is_enable:
    Send_Command_and_Get_Response("enable\n", "#", False)

# Disable more
Send_Command_and_Get_Response("terminal length 0\n", "#", False)

strConfig = "conf t\n"
strConfig + "int g0/0/1\n"
strConfig + "ip address 192.168.1.21 255.255.255.0\n"
strConfig + "no shut\n"
strConfig + "exit\n"
strConfig + "ethernet-internal subslot 1/0\n"
strConfig + "platform switchport svi\n"
strConfig + "end\n"
print strConfig
Send_Command_and_Get_Response(strConfig, "#", False)

Send_Command_and_Get_Response("ping 192.168.1.1\n", "#", True)

#reload the router and check for completion
time.sleep(1)
strReload = "reload\n yes\n"
Send_Command_and_Get_Response(strReload, "#", True)

is_reloading = None 
while (is_reloading) not in ">":
    time.sleep(7)
    is_loading = shell.recv(1024)
print "Router has finished reloading and is ready for config."


# Close the SSH connection
client.close()
sys.exit(-1)

0 个答案:

没有答案